/**
 * Created by yunpeng on 2015/3/26.
 */
var starterModule = angular.module('starter',['starter.controllers','starter.orderControllers','starter.centerControllers', 'starter.services','starter.centerSrvices','starter.orderServices','ui.router','ngAnimate'])
    .run(['$rootScope', '$state', '$stateParams','$window','AuthenticationService',function($rootScope, $state, $stateParams,$window,AuthenticationService) {

   /*     $rootScope.$on('$routeChangeStart', function(event, next, current) {
            //redirect only if both isLogged is false and no token is set
            if (next != null && next.access != null && next.access.requiredLogin
                && !AuthenticationService.isLogged && !$window.sessionStorage.token) {

                $state.go('/');
            }
        });*/

        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
            if (toState != null && toState.access != null && toState.access.requiredLogin
                && !AuthenticationService.isLogged && !localStorage.getItem('token')) {//判断token状态，验证失败阻止进入其他url//$window.sessionStorage.token

                $state.go('login');
                event.preventDefault();
            }

            if(toState.url.indexOf('transfer')>-1){
                setCo();
                changeCo(1);

            }else if(toState.url.indexOf('myTransfer')>-1){
                setCo();
                changeCo(2);

            }else if(toState.url.indexOf('myOrders')>-1){
                setCo();
                changeCo(3);

            }else if(toState.url.indexOf('center')>-1){
                setCo();
                changeCo(4);
            }

            /*$rootScope.setColor = function(index){
                setCo();
                changeCo(index);
                console.log('sss');
            }*/
            function setCo(){
                $rootScope.num1=2;
                $rootScope.num2=2;
                $rootScope.num3=2;
                $rootScope.num4=2;
            }

            function changeCo(index){
                switch (index){
                    case 1:
                        $rootScope.num1=1;
                        break;
                    case 2:
                        $rootScope.num2=1;
                        break;
                    case 3:
                        $rootScope.num3=1;
                        break;
                    case 4:
                        $rootScope.num4=1;
                        break;
                }
            }

        });


        $rootScope.goMain = function(){
            $state.go('/');
        }
        }
    ])
    .config(['$stateProvider', '$urlRouterProvider','$httpProvider',function($stateProvider, $urlRouterProvider,$httpProvider){
        $httpProvider.interceptors.push('TokenInterceptor');
        $stateProvider
            .state('login',{
                url:'/login',
                templateUrl:'view/logon/login.html',
                controller:'LoginCtrl'
         })
            .state('/',{
                url:'/',
                templateUrl:'view/main/main.html',
                controller:'MainCtrl',
                access: { requiredLogin: false }
            })
            .state('tab',{
                url:'/tab',
                abstract:true,
                templateUrl:'view/tabs.html',
                /*controller:'TabCtrl',*/
                access: { requiredLogin: true }
            })
            .state('tab.transfer',{
                url:'/transfer',
                templateUrl:'view/transfer/transfer.html',
                controller:'TransferCtrl',
                access: { requiredLogin: true }

         })
            .state('tab.myTransfer',{
                url:'/myTransfer/:random',
                templateUrl:'view/transfer/myTransfer.html',
                controller:'MyTransferCtrl',
                access: { requiredLogin: true }
            })
            .state('query',{
                url:'/query/:isWechat',
                templateUrl:'view/query/query.html',
                controller:'Query'
            })
            .state('tab.myOrders',{
                url:'/myOrders',
                templateUrl:'view/order/order1.html',
                controller:'MyOrderCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.center',{
                url:'/center',
                templateUrl:'view/center/center.html',
                controller:'CenterCtrl',
                access: { requiredLogin: true }
            })
            .state('register',{
                url:'/register',
                templateUrl:'view/logon/register.html',
                controller:'RegisterCtrl'
            })
            .state('resetPass',{
                url:'/resetPass',
                templateUrl:'view/logon/resetPass.html',
                controller:'ResetPassCtrl'
            })
            .state('tab.outDetails',{
                url:'/myTransfer/outDetails/:startstation/:endstation/:starttime/:endtime/:type/:num/:carnum/:nums/:infoid',
                templateUrl:'view/transfer/outDetails.html',
                controller:'OutDetails',
                access: { requiredLogin: true }
            })
            .state('tab.myTransfer2',{
                url:'/myTransfer/myTransfer2/:inforid/:name/:phone',
                templateUrl:'view/transfer/myTransfer2.html',
                controller:'myTransfer2',
                access: { requiredLogin: true }
            })
            .state('tab.companyDet',{
                url:'/myTransfer/companyDet/:inforid/:userid',
                templateUrl:'view/transfer/companyDet.html',
                controller:'companyDet',
                access: { requiredLogin: true }
            })
            .state('tab.citys',{
                url:'/citys/:type',//1始发地 2目的地
                templateUrl:'view/transfer/citys.html',
                controller:'CitysCtrl'/*,
                access: { requiredLogin: true }*/
            })
            .state('AddCitys',{
                url:'/AddCitys/:type',//1始发地 2目的地
                templateUrl:'view/query/citys.html',
                controller:'AddCitys'/*,
                access: { requiredLogin: true }*/
            })
            .state('tab.transferAddCar',{
                url:'/transferAddCar',//1始发地 2目的地
                templateUrl:'view/transfer/transferAddCar.html',
                controller:'TransferAddCarCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.getCarBrandList',{
                url:'/getCarBrandList',//1始发地 2目的地
                templateUrl:'view/transfer/carbrand.html',
                controller:'CarBrandListCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.getCarNumList',{
                url:'/getCarNumList',//1始发地 2目的地
                templateUrl:'view/transfer/carnum.html',
                controller:'CarNumListCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.carlist',{
                url:'/carlist',//1始发地 2目的地
                templateUrl:'view/transfer/carlist.html',
                controller:'CarListCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.complete',{
                url:'/complete/:isOk',//1始发地 2目的地
                templateUrl:'view/transfer/complete.html',
                controller:'CompleteCtrl',
                access: { requiredLogin: true }
            })
            .state('tab.completeQuo',{  //接受报价后
                url:'/completeQuo/:isOk',
                templateUrl:'view/transfer/complete01.html',
                controller:'CompleteCtrlQuo',
                access: { requiredLogin: true }
            })
            .state('tab.cropper',{
                url:'/cropper/:scale1/:scale2/:width/:height/:urltype',//
                templateUrl:'view/cropper.html',
                controller:'CropperCtrl',
                access: { requiredLogin: true }
            });
         $urlRouterProvider.otherwise('/');
    }])
   .directive('ngLoad',['$http','$compile','MyTransferService','$stateParams',function($http,$compile,MyTransferService,$stateParams){//自定义指令
    return{
        restrict: 'A',//
        templateUrl:'./view/transfer/ulcontent.html',
        link:function(scope,element,attrs,controller){
            $('#contentu').css('min-height',$(window).height()-92+'px');
            scope.query = {sort:'createtime',order:'desc',page:1,rows:10};
            //初始化列表
            var arrs=[];
            if($stateParams.random=='update'){
                scope.query.page=1;//从第一页开始查询
                var  promise = $http({
                    method:'POST',
                    url:'/myTransfer',
                    data:{
                        query : {sort:'createtime',order:'desc',page:1,rows:10}
                    }
                });
                promise.success(function(data,status) {
                    var arrss=[];
                    scope.datas = data.rows;
                    MyTransferService.getMytransferData().datas = scope.datas;//更新service数据
                    scope.query.page+=1;//查询成功页数加一
                    for(var i=0;i<data.rows.length;i++){
                        var arr=data.rows[i].num.split(',');
                        var ss=0;
                        for(var j=0;j<arr.length;j++){
                            ss += parseInt(arr[j]);
                        }
                        arrss.push(ss);
                    }
                    scope.nums=arrss;
                    setTimeout(function(){//因为有冲突等会执行scope.$apply();
                        scope.$apply(element);
                        if(scope.myScroll){
                            scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                        }
                    },500);});
            }else{
                if(!MyTransferService.getMytransferData().datas.length>0){//判断数据是否加载过，存在不去请求服务器
                    var  promise = $http({
                        method:'POST',
                        url:'/myTransfer',
                        data:{
                            query:scope.query
                        }
                    });
                    promise.success(function(data,status) {
                        scope.datas = data.rows;
                        MyTransferService.getMytransferData().datas = scope.datas;
                        scope.query.page+=1;
                        /*  var num=data.rows[0].num;
                         var nums=num.split(",");*/
                        for(var i=0;i<scope.datas.length;i++){
                            var arr=scope.datas[i].num.split(',');
                            var ss=0;
                            for(var j=0;j<arr.length;j++){
                                ss += parseInt(arr[j]);
                            }
                            arrs.push(ss);
                        }
                        scope.nums=arrs;
                        setTimeout(function(){//因为有冲突等会执行scope.$apply();
                            scope.$apply(element);
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        },500);
                    });

                }
            }
            //angular.element(element.children().eq(0)).toggleClass('a1');
            function pullDownAction(){//下拉刷新调用
                /* var el, li, i;*/
                 //el = document.querySelector("#scroller ul");
                    /*for (i=0; i<3; i++) {
                    li = document.createElement("li");
                    li.innerHTML = $compile('<input type="button" ng-click="alert1()" value="dddddd"/>')(scope);//Firefox  does not suppose innerText, use innerHTML instead.)//Firefox  does not suppose innerText, use innerHTML instead.
                    el.insertBefore(li, el.childNodes[0]);
                    }
                       var dd = $compile('<input type="button" ng-click="alert1()" value="dddddd"/><input type="button" ng-click="alert1()" value="ddddddaaddd"/>' +
                       '<div style="color: #CD235C;height: 3em;">asdsad</div>')(scope);
                       element.append(dd);*/
            }
            pull(scope,"wrapper",function(pull){
                if('pullDown'==pull) {//下拉刷新
                    scope.query.page=1;//从第一页开始查询
                    var  promise = $http({
                        method:'POST',
                        url:'/myTransfer',
                        data:{
                            query : scope.query
                        }
                    });
                    promise.success(function(data,status) {
                        scope.datas = data.rows;
                        MyTransferService.getMytransferData().datas = scope.datas;//更新service数据
                        scope.query.page+=1;//查询成功页数加一
                        setTimeout(function(){//因为有冲突等会执行scope.$apply();
                            scope.$apply(element);
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        },500);

                    }).error(function (data,status) {
                        if(scope.myScroll){
                            scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                        }
                    });
                }else{
                    var  promise = $http({
                        method:'POST',
                        url:'/myTransfer',
                        data:{
                            query : scope.query
                        }
                    });
                    promise.success(function(data) {
                        scope.query.page+=1;//查询成功页数加一
                        if(data.rows.length>0){
                            scope.datas = scope.datas.concat(data.rows);
                            MyTransferService.getMytransferData().datas = scope.datas;//service更新数据
                            var num=data.rows[0].num;
                            var nums=num.split(",");
                            for(var i=0;i<data.rows.length;i++){
                                var arr=data.rows[i].num.split(',');
                                var ss=0;
                                for(var j=0;j<arr.length;j++){
                                    ss += parseInt(arr[j]);
                                }
                                arrs.push(ss);
                            }
                            scope.nums=arrs;
                        }

                        setTimeout(function(){//因为有冲突等会执行scope.$apply();
                            scope.$apply(element);
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        },500);

                    }).error(function (data,status) {
                        if(scope.myScroll){
                            scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                        }
                    });
                }
            });
            //初始化绑定iScroll控件
            document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
            //document.addEventListener('DOMContentLoaded', loaded, false);

            if(MyTransferService.getMytransferData().datas.length>0){//待myScroll初始化完成后刷新页面数据
                scope.datas = MyTransferService.getMytransferData().datas;
                scope.query.page+=1;
                for(var i=0;i<scope.datas.length;i++){
                    var arr=scope.datas[i].num.split(',');
                    var ss=0;
                    for(var j=0;j<arr.length;j++){
                        ss += parseInt(arr[j]);
                    }
                    arrs.push(ss);
                }
                scope.nums=arrs;
                setTimeout(function(){//因为有冲突等会执行scope.$apply();
                    scope.$apply(element);
                    if(scope.myScroll){
                        scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                    }
                },500);
                return;
            }


        }
    }
}]).directive('ngLoaded',['$http','$compile','$stateParams',function($http,$compile,$stateParams){//自定义指令
        return{
            restrict: 'A',//
            templateUrl:'./view/transfer/quotation.html',
            link:function(scope,element,$state,attrs,controller){
                $('#content').css('min-height',$(window).height()-92+'px');
                //初始化列表

                scope.query = {sort:'starttime',order:'desc',page:1,rows:10};
                var inforid=$stateParams.inforid;
                var name=$stateParams.name;
                var myphone=$stateParams.phone;
                var  promise = $http({
                    method:'POST',
                    url:'/quotation',
                    data:{
                        query:scope.query,
                        inforid:inforid
                    }
                });
                promise.success(function(data) {
                    scope.query.page+=1;
                    scope.datas = data.rows;
                    scope.name=name;
                    scope.myphone=myphone;
                    if(data.rows.length==0){
                        scope.show=true;
                    }else{
                        scope.show=false;
                    }
                    scope.inforid=inforid;
                    scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];
                    setTimeout(function(){//因为有冲突等会执行scope.$apply();
                        scope.$apply(element);
                        if(scope.myScroll){
                            scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)

                        }
                    },500);
                });
                //angular.element(element.children().eq(0)).toggleClass('a1');
                function pullDownAction(){//下拉刷新调用
                    /* var el, li, i;*/
                    //el = document.querySelector("#scroller ul");
                    /*for (i=0; i<3; i++) {
                     li = document.createElement("li");
                     li.innerHTML = $compile('<input type="button" ng-click="alert1()" value="dddddd"/>')(scope);//Firefox  does not suppose innerText, use innerHTML instead.)//Firefox  does not suppose innerText, use innerHTML instead.
                     el.insertBefore(li, el.childNodes[0]);
                     }
                     var dd = $compile('<input type="button" ng-click="alert1()" value="dddddd"/><input type="button" ng-click="alert1()" value="ddddddaaddd"/>' +
                     '<div style="color: #CD235C;height: 3em;">asdsad</div>')(scope);
                     element.append(dd);*/
                }
                pull(scope,"wrapper",function(pull){
                    if('pullDown'==pull) {//下拉刷新
                        scope.query.page=1;
                        var  promise = $http({
                                method:'POST',
                                url:'/quotation',
                                data:{
                                    query:scope.query,
                                    inforid:inforid
                                }
                            });
                            promise.success(function(data) {
                                scope.query.page+=1;
                                scope.datas = data.rows;
                                scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];
                                setTimeout(function(){//因为有冲突等会执行scope.$apply();
                                    scope.$apply(element);
                                    if(scope.myScroll){
                                        scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                                    }
                                },500);

                        }).error(function (data,status) {
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        });
                    }else{
                        var  promise = $http({
                            method:'POST',
                            url:'/quotation',
                            data:{
                                query:scope.query,
                                inforid:inforid
                            }
                        });
                        promise.success(function(data) {
                            scope.query.page+=1;
                            scope.datas = scope.datas.concat(data.rows);
                            scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];
                            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                                scope.$apply(element);
                                if(scope.myScroll){
                                    scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                                }
                            },500);

                        }).error(function (data,status) {
                            if(scope.myScroll){
                                scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                            }
                        });
                    }
                });
                //初始化绑定iScroll控件
                document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
                //document.addEventListener('DOMContentLoaded', loaded, false);

            }
        }
    }]).directive('ngSlider',['$http','$compile',function($http,$compile){//自定义指令
        return{
            restrict: 'A',//
            //templateUrl:'./view/transfer/quotation.html',
            link:function(scope,element,attrs,controller){


            }
        }
    }]);

/**
 * 下拉刷新调用此方法回调callback(pull) pull=='pullDown'下拉 pull=='pullUp'上拉
 * @param scope
 * @param callback
 */
function pull(scope,id,callback){
    scope.myScroll="#"+id;
    // var myScroll,
    scope.pullDownEl= 0;
    scope.pullDownOffset= 0;
    scope.pullUpEl= 0;
    scope.pullUpOffset= 0;
    scope.generatedCount = 0;

    //function loaded() {
    scope.pullDownEl = document.querySelector("#pullDown");
    if (scope.pullDownEl) {
        scope.pullDownOffset = scope.pullDownEl.offsetHeight;
    } else {
        scope.pullDownOffset = 0;
    }
    scope.pullUpEl = document.querySelector("#pullUp");
    if (scope.pullUpEl) {
        scope.pullUpOffset = scope.pullUpEl.offsetHeight;
    } else {
        scope.pullUpOffset = 0;
    }

    console.log(" scope.pullDownOffset:"+ scope.pullDownOffset);
    console.log("scope.pullUpOffset:"+scope.pullUpOffset);

    //Options of IScroll
    var myOptions = {
        mouseWheel: true,click:true,
        scrollbars: false,
        fadeScrollbars: true,
        probeType: 1,
        startY: - scope.pullDownOffset
    };
    scope.myScroll = new IScroll("#"+id,myOptions);
    console.log("maxScrollY-1:"+scope.myScroll.maxScrollY);
    _maxScrollY = scope.myScroll.maxScrollY = scope.myScroll.maxScrollY + scope.pullUpOffset;
    console.log("maxScrollY-2:"+scope.myScroll.maxScrollY);

    var isScrolling = false;

    //Event: scrollStart
    scope.myScroll.on("scrollStart", function() {
        if(this.y==this.startY){
            isScrolling = true;
        }
        console.log("start-y:"+this.y);
    });

    //Event: scroll
    scope.myScroll.on("scroll", function(){
        if (this.y >= 5 && scope.pullDownEl && !scope.pullDownEl.className.match("flip")) {
            scope.pullDownEl.className = "flip";
            scope.pullDownEl.querySelector(".pullDownLabel").innerHTML = "释放立即刷新";
            //this.minScrollY = 0;
        } else if (this.y < 5  && scope.pullDownEl && scope.pullDownEl.className.match("flip")) {
            scope.pullDownEl.className = "";
            scope.pullDownEl.querySelector(".pullDownLabel").innerHTML = "下拉刷新";
            //this.minScrollY = - scope.pullDownOffset;
        }else if (this.y <= (_maxScrollY - scope.pullUpOffset) && scope.pullUpEl && !scope.pullUpEl.className.match("flip")) {
            scope.pullUpEl.className = "flip";
            scope.pullUpEl.querySelector(".pullUpLabel").innerHTML = "释放立即刷新";
            //this.maxScrollY = this.maxScrollY;
            this.maxScrollY = this.maxScrollY - scope.pullUpOffset;
        } else if (this.y > (_maxScrollY - scope.pullUpOffset) && scope.pullUpEl && scope.pullUpEl.className.match("flip")) {
            scope.pullUpEl.className = "";
            scope.pullUpEl.querySelector(".pullUpLabel").innerHTML = "上拉加载更多";
            //this.maxScrollY = scope.pullUpOffset;
            this.maxScrollY = this.maxScrollY + scope.pullUpOffset;
        }

        console.log("y:"+this.y);
    });

    //Event: scrollEnd
    scope.myScroll.on("scrollEnd", function() {
        console.log("scroll end");
        console.log("directionY:"+this.directionY);
        console.log("y1:"+this.y);
        console.log("maxScrollY-3:"+this.maxScrollY);
        if (scope.pullDownEl && !scope.pullDownEl.className.match("flip") && this.y > this.options.startY) {
            console.log("resume");
            this.scrollTo(0, this.options.startY,800);
        }
        else if (scope.pullDownEl && scope.pullDownEl.className.match("flip")){
            scope.pullDownEl.className = "loading";
            scope.pullDownEl.querySelector(".pullDownLabel").innerHTML = "加载中...";
            // Execute custom function (ajax call?)
            if (isScrolling) {
                console.log("before pull down action:"+this.y);
                //pullDownAction();
                callback('pullDown');
                console.log("after pull down action:"+this.y);
            }
        }
        else if (scope.pullUpEl && scope.pullUpEl.className.match("flip")) {
            console.log("pull up loading");
            scope.pullUpEl.className = "loading";
            scope.pullUpEl.querySelector(".pullUpLabel").innerHTML = "加载中...";
            // Execute custom function (ajax call?)
            if (isScrolling) {
                console.log("before pull up action:"+this.y);
                //pullUpAction();
                callback('pullUp');

                console.log("after pull up action:"+this.y);
            }
        }
        isScrolling = false;
    });

    //Event: refresh
    scope.myScroll.on("refresh", function() {

        console.log("maxScrollY-4:"+this.maxScrollY);
        _maxScrollY = this.maxScrollY = this.maxScrollY+scope.pullUpOffset;
        console.log("maxScrollY-5:"+this.maxScrollY);

        if (scope.pullDownEl  && scope.pullDownEl.className.match("loading")) {
            scope.pullDownEl.className = "";
            scope.pullDownEl.querySelector(".pullDownLabel").innerHTML = "下拉刷新";
            this.scrollTo(0,this.options.startY,0);
        } else if (scope.pullUpEl && scope.pullUpEl.className.match("loading")) {
            scope.pullUpEl.className = "";
            scope.pullUpEl.querySelector(".pullUpLabel").innerHTML = "上拉加载更多";
            this.scrollTo(0,this.maxScrollY,0);
        }

        console.log("refresh finished!");
    });

    setTimeout(function () { document.getElementById(id).style.left = "0"; }, 800);

    //}

};/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.controllers', [])
    .controller('MainCtrl',function($scope,$state,$window,MainService,AuthenticationService){
        if(localStorage.getItem('token')){
            AuthenticationService.isLogged = true;
        }
        $scope.islogin = AuthenticationService.isLogged;
        $('#slides2').slidesjs({
            width: 940,
            height: 528,
            navigation: false,
            start: 3,
            play: {
                auto: true
            }
        });

        $scope.myScroll = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll

        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        $scope.popQuery = false;
        $scope.go = function(type){
            switch (type){
                case 1:
                    $state.go('tab.transfer');
                    break;
                case 2:
                    $state.go('tab.myTransfer',{random:false});
                    break;
                case 3:
                    $state.go('tab.myOrders');
                    break;
                case 4:
                    $state.go('tab.center');
                    break;
                case 5://注销
                    //$state.go('tab.center');
                    /*$state.go('query');*/
                    $scope.popQuery = true;
                    $('#pop1button1').click(function(e)
                    {
                        $scope.popQuery=false;
                        setTimeout(function(){
                            $scope.$apply();
                        },500);

                    });

                    break;
                    /*AuthenticationService.isLogged = false;
                    localStorage.removeItem('token');
                    localStorage.removeItem('user');*/
                    /*delete $window.sessionStorage.token;
                    delete $window.sessionStorage.user;*/
                   /* window.localStorage.setItem('token',data.token);
                    window.localStorage.setItem('user',JSON.stringify(data.user));*/

                    break;
                case 6:
                    $state.go('register');
                    break;
                case 7:
                    $state.go('login');
                    break;
                case 8:
                    $state.go('tab.mySuggest');
                    break;
            }


        }
    })
    .controller('TransferCtrl',function($scope,$state,$timeout,$interval,LoginService,$location,TransferService){
        //alert(TransferService.getInforData().startCityId+' '+TransferService.getInforData().startCity);
        //$scope.citys =[{name:'广州'},{name:'哈尔滨'},{name:'西安'},{name:'南京'},{name:'哈尔滨'},{name:'西安'},{name:'南京'}];

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.inforData = {};
        if(!TransferService.getCityList().length>0){//如果初始化过城市则不再请求，直接赋值到页面
            TransferService.getCitys($scope);
        }/*else{*/
            $scope.inforData = TransferService.getInforData();
        //}
        console.log(TransferService.getInforData());
        $scope.pop1=false;
        $scope.showinput=false;
        $scope.isDisabled=true;
        var msgcode;
        $scope.user = {btnVal:' 获取验证码 '};


        if(localStorage.getItem('user')){
            $scope.inforData.phone = Number(JSON.parse(localStorage.getItem('user')).phone)
        }

        var firstphone=$scope.inforData.phone;
        $scope.updatephone=firstphone;
        $scope.getCode1=function(phone){
            if(!isNaN($scope.user.btnVal)){
                return;
            }
            if(phone==null||phone.length<11){
                $scope.pop1 = true;
                $scope.content = '请输入正确手机号码';
                return false;
            }
            LoginService.getCode(phone,'phoneCode')
                .success(function(data,status){
                    if(data=='err'){
                        $scope.pop1 = true;
                        $scope.content = '验证码获取失败！';
                        return false;
                    }
                    msgcode=data;
                    $scope.user.btnVal=60;
                    var timer = $interval(function(){
                        $scope.user.btnVal-=1;
                        if($scope.user.btnVal==0){
                            $scope.user.btnVal='  重新获取  ';
                            msgcode=undefined;
                            $interval.cancel(timer);
                        }
                    },1000);

                }).error(function (data,status) {
                    $scope.pop1 = true;
                    $scope.content = '验证码获取失败！';
                    return false;
                });
        }
        $scope.goNext = function(){
            //console.log($scope.inforData.startTime+"----"+new Date().toLocaleDateString());
            function daysBetween(DateOne,DateTwo)
            {
                var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));
                var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);
                var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));

                //var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('/'));
                //var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('/')+1);
                //var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('/'));
                var date = new Date();
                var month = date.getMonth()+1;
                var day = date.getDate();
                if(month<10){
                    month = '/0'+month;
                }else{
                    month = '/'+month
                }
                if(day<10){
                    day = '/0'+day;
                }else{
                    day = '/'+day;
                }
                var dd = date.getFullYear()+month+day;
                var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(dd))/86400000);
                return cha;
            }
            var isstartDate=daysBetween($scope.inforData.startTime);
            var isendDate=daysBetween($scope.inforData.endTime);

            if($scope.inforData.username==''||$scope.inforData.phone==''||new Date($scope.inforData.startTime).getTime()>new Date($scope.inforData.endTime).getTime()||isstartDate<0||isendDate<0) {
                if (new Date($scope.inforData.startTime).getTime() > new Date($scope.inforData.endTime).getTime()) {
                    $scope.pop1 = true;
                    $scope.content = "到达日期不能早于出发日期。";
                    return false;
                } else if($scope.inforData.username==''||$scope.inforData.phone==''){
                    $scope.pop1 = true;
                    $scope.content = "请填写用户姓名和手机号码！";
                    return false;
                }else if(isstartDate<0||isendDate<0){
                    $scope.pop1 = true;
                    $scope.content = "启程或到货日期不能小于当前日期！";
                    return false;
                }

            }else{
                if($scope.inforData.phone==firstphone){
                    $state.go('tab.transferAddCar');
                }else{
                    if($scope.code){
                        if($scope.code==msgcode){
                            $state.go('tab.transferAddCar');
                        }else{
                            $scope.pop1 = true;
                            $scope.content="验证码错误，请重新输入！";
                            return false;
                        }
                    }else{
                        $scope.pop1 = true;
                        $scope.content="请验证修改后的手机号码！";
                        return false;
                    }

                }
            }
        }

     /* $scope.pop1button = document.getElementById('pop1button');
        $scope.pop1button.addEventListener('tap', function (e) {

            $scope.pop1=false;
            setTimeout(function(){
                    $scope.$apply();
                },500)
        }, false);*/
        $('#pop1button').click(function(e)
        {
            $scope.pop1=false;
            setTimeout(function(){
                $scope.$apply();
            },500);

        });
        //$scope.inforData.phone = Number(JSON.parse(localStorage.getItem('user')).phone);
        $scope.selectCity = function(type){//1起点 2目的地
            //alert(type);
            TransferService.getInforData().username = $scope.inforData.username;
            TransferService.getInforData().phone = $scope.inforData.phone;
            /*TransferService.getInforData().startTime = $("#date1").val();
            TransferService.getInforData().endTime = $("#date2").val();*/
            $state.go('tab.citys',{type:type});
        }
        $("#dtBox").DateTimePicker({//各平台兼容性不同，创建了两个实例
            addEventHandlers: function()
            {
                var dtPickerObj = this;

                $("#pickerButton").click(function(e)
                {
                    e.stopPropagation();
                    dtPickerObj.showDateTimePicker($("#date1"));
                });

            }
        });
        $("#dtBox1").DateTimePicker({

            addEventHandlers: function()
            {
                var dtPickerObj = this;

                $("#pickerButton1").click(function(e)
                {
                    e.stopPropagation();
                    dtPickerObj.showDateTimePicker($("#date2"));
                    dtPickerObj._setCurrentDate();
                });
            }
        });

        $('#date1').bind('change',function(){//jquery监听隐藏文本框值变化

            TransferService.getInforData().startTime = this.value;
            $scope.inforData.startTime = this.value;

            $scope.$apply();
            $scope.myScroll.refresh();

        });
        $('#date2').bind('change',function(){
            //if(new Date($scope.inforData.startTime)>new Date(this.value)){
            //    alert('到达日期不能早于出发日期');
            //    return;
            //}
            TransferService.getInforData().endTime = this.value;
            $scope.inforData.endTime = this.value;

            $scope.$apply();
            $scope.myScroll.refresh();
        });

        $scope.$watch('inforData.phone',function(newValue,oldValue, scope){
            if(newValue!=oldValue){
                setTimeout(function(){
                    $scope.$apply();
                    $scope.myScroll.refresh();
                },500);

            }

        });

    })
    .controller('MyTransferCtrl',function($scope,$state,MyTransferService){
        //$scope.datas=MyTransferService.getMytransferData().datas;

        $scope.go = function(go,trans,nums){
            if(go==1){
                $state.go('tab.outDetails',{startstation:trans.startstation,endstation:trans.endstation,starttime:trans.starttime,endtime:trans.endtime,type:trans.type,num:trans.num,carnum:trans.carnum,nums:nums,infoid:trans.id});
            }else if(go==2){
                $state.go('tab.myTransfer2',{inforid:trans.id,name:trans.username,phone:trans.phone});
            }

        }
    })
    .controller('myTransfer2',function($scope,$rootScope,$http,$state,LoginService,$stateParams,TransferService){
      /*  $scope.myScroll = new IScroll('#wrapperTran', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
*/
        $scope.hid=false;
        $scope.pop1=false;
        //$scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        //document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.goBack = function() {
            $state.go('tab.myTransfer');
        }
        $scope.goCompany=function(inforid,userid){
            $state.go('tab.companyDet',{inforid:inforid,userid:userid});
        }
        $scope.accept=function(inforid,data){
            $scope.pop1=true;
            $scope.content="确定接受报价吗？";
            $scope.inforid=inforid;
            $scope.data=data;
            $scope.typebtn=1;
            console.log(data);
        }
        $scope.cancelPop=function(){
            $scope.pop1=false;
        }
        $scope.confirm=function(typebtn,inforid,data,name,myphone){
            var user = $scope.user = JSON.parse(localStorage.user);
            console.log(data);
            if(typebtn==1){
                $scope.pop1=false;
                var promise = $http({
                    method:'POST',
                    url:'/accept',
                    data:{
                        inforid:inforid,
                        data:data
                    }
                });
                promise.success(function(datas) {
                    console.log(datas);
                    if(datas){
                        if(user.nickname){
                            LoginService.accept(data.phone,user.nickname,myphone)
                                .success(function(data,status){
                                }
                            );
                        }else{
                            LoginService.accept(data.phone,false,myphone)
                                .success(function(data,status){
                                }
                            );
                        }

                        $rootScope.refreshOrder = true;
                        $state.go('tab.completeQuo',{isOk:data});
                    }else{
                        $scope.pop1=true;
                        $scope.content="接受报价失败，请重试。";
                        $scope.typebtn=2;
                    }
                });
            }else{
                $scope.pop1=false;
            }

        }

    })
    .controller('Query',function($scope,$state,$stateParams,$rootScope,$http,$location,TransferService){
        if(!$rootScope.isWechat){
            $rootScope.isWechat = $stateParams.isWechat;
        }
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        $scope.subQuery = function(inforData){  //点击添加
            var promise = $http({
                method:'POST',
                url:'/queryPrice',
                data:{
                    inforData:inforData
                }
            });
            promise.success(function(data) {
                $scope.num=data.num;
                $scope.price=data.price;
            });
        }

        $scope.inforData = {};
        if(!TransferService.getCityList().length>0){//如果初始化过城市则不再请求，直接赋值到页面
            TransferService.getCitys($scope);
        }else{
            $scope.inforData = TransferService.getInforData();
        }

        $scope.selectCity = function(type){//1起点 2目的地
            $state.go('AddCitys',{type:type});
        }
    })
    .controller('AddCitys',function($scope,$state,$stateParams,TransferService){
        $scope.citys = TransferService.getCityList();
        $scope.allcitys = TransferService.getAllCitys();
        $scope.provinces = TransferService.getProvince();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        $scope.myScroll1 = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
            $scope.myScroll1.refresh();
        },500);
        $scope.goBack = function(){
            $state.go('query');
        };
        $scope.selectCity = function(id,province,city){//判断上一页面传来的值是1则改变事发地点2为目的地
            if($stateParams.type==1){
                TransferService.getInforData().startCityId = id;
                TransferService.getInforData().startCity = province+" "+city;

            }else if($stateParams.type==2){
                TransferService.getInforData().endCityId = id;
                TransferService.getInforData().endCity = province+" "+city;
            }
            $state.go('query');
        };

        $scope.selectProvince = function(province){/*选择省份*/
            var citys = [];
            for(var i=0;i<$scope.allcitys.length;i++){
                if(province==$scope.allcitys[i].province){
                    citys.push($scope.allcitys[i]);
                }
            }
            $scope.citys = citys;
            //this.style.backgroundColor=this.style.backgroundColor==''?'#a00':'';return false;
            /*$(this).css('color','#a00');*/
            setTimeout(function(){
                $scope.$apply();
                $scope.myScroll1.refresh();

            },500);
        }
    })

    .controller('OutDetails',function($scope,$state,$http,$stateParams,TransferService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        var startstation=$stateParams.startstation;
        var endstation=$stateParams.endstation;
        var starttime=$stateParams.starttime;
        var endtime=$stateParams.endtime;
        var type=$stateParams.type;
        var num=$stateParams.num.split(',');
        var carnums=$stateParams.carnum;
        var nums=$stateParams.nums;
        var infoid=$stateParams.infoid;
        var brand=carnums.split(',');
        $scope.popup=2;
        var  promise = $http({
            method:'POST',
            url:'/outDetails',
            data:{
                carnum:carnums
            }
        });
        promise.success(function(data,status) {

            $scope.startstation = startstation;
            $scope.endstation=endstation;
            $scope.starttime=starttime;
            $scope.endtime=endtime;
            $scope.carnum=num; //辆数
            $scope.type=type; //类型(板车or拼装)
            $scope.infoid=infoid; //发车单id
            var docs=[]; //品牌id，品牌，型号

            for(var i=0;i<brand.length;i++){
                for(var j=0;j<data.result.length;j++){
                    if(brand[i]==data.result[j].id.toString()){
                        var doc={};
                        doc.bid=data.result[j].id.toString(); //品牌id
                        doc.num=data.result[j].num;  // 型号
                        doc.carbrand=data.result[j].carbrand; //品牌
                        docs.push(doc);
                    }else{
                    }
                }
            }

            $scope.result = docs;

            //删除拼车
            //$scope.delete = function($index){
            //    if(num.length>1){
            //        num.splice($index,1);
            //        docs.splice($index,1);
            //        brand.splice($index,1);
            //        infoNum=num;
            //        infoBrand=brand;
            //    }else{
            //        alert('订单不能为空。')
            //    }
            //}
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                //$scope.$apply(element);
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $scope.pop1=false;
        $scope.pop = function(num,index,doc){
            if(num==1){  //1为取消
                $scope.pop1=true;
                $scope.content="确定取消此发布单吗？";
                $scope.typebtn=1;
            }else if(num==2){ //2为修改
                if(doc==0){
                    $scope.pop1=true;
                    $scope.content="确定修改此发布单吗？";
                    $scope.typebtn=2;
                    $scope.ind=index;
                    $scope.docc=0;
                }else{
                    $scope.pop1=true;
                    $scope.content="确定修改此发布单吗？";
                    $scope.typebtn=2;
                    $scope.ind=index;
                    $scope.docc=doc;
                }
            }
        }
        $scope.cancelPop = function(){
            $scope.pop1=false;
        }
        $scope.confirm = function(typebtn,infoid,type,index,doc){
            if(typebtn==1){
                var  promise = $http({
                    method:'POST',
                    url:'/updateCancel',
                    data:{
                        id:infoid
                    }
                });
                promise.success(function(data) {
                    $state.go('tab.myTransfer',{random:'update'});
                });
            }else if(typebtn==2){
                if(type==1){
                    if(num.length>1){
                        num.splice(index,1);
                        doc.splice(index,1);
                        brand.splice(index,1);
                        infoNum=num;
                        infoBrand=brand;
                        var  promise = $http({
                            method:'POST',
                            url:'/updateOut',
                            data:{
                                carnum:infoBrand,
                                num:num,
                                id:infoid
                            }
                        });
                        promise.success(function(data) {
                            if(data){
                                $scope.pop1=false;
                                //$state.go('tab.myTransfer',{random:'update'});
                            }
                        });
                    }else{
                        $scope.content="发布单车辆不能为空。";
                    }
                }else{
                    if(num.length>1){
                        num.splice(index,1);
                        if(doc==12){
                            brand[0]=brand[0]-1;
                        }else{
                            brand[1]=brand[1]-1;
                        }
                        infoSNum=num;
                        infoSBrand=brand;
                        var  promise = $http({
                            method:'POST',
                            url:'/updateScooter',
                            data:{
                                num:num,
                                id:infoid,
                                carnum:infoSBrand
                            }
                        });
                        promise.success(function(data) {
                            if(data){
                                $scope.pop1=false;
                                //$state.go('tab.myTransfer',{random:'update'});
                            }
                        });
                    }else{
                        $scope.content="发布单车辆不能为空。";
                    }

                }
            }
        }
        $scope.goBack = function(){
            $state.go('tab.myTransfer');
        }
    })
    .controller('companyDet',function($scope,$state,$http,$stateParams,TransferService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, true);
        var inforid=$stateParams.inforid;
        var userid=$stateParams.userid;
        var  promise = $http({
            method:'POST',
            url:'/companyDet',
            data:{
                userid:userid
            }
        });
        promise.success(function(data) {
            $scope.introduce=data[0].introduce; //用户自我介绍
            $scope.address=data[0].address;  //地址
            $scope.company=data[0].company;  //公司名称
            $scope.authstate=data[0].authstate; //是否认证
            $scope.attitude=data[0].attitude; //服务态度
            $scope.care=data[0].care; //关心货物
            $scope.corresponds=data[0].corresponds; //符合程度
            $scope.evaluationnum=data[0].evaluationnum; //评分总人数
            $scope.licences=data[0].licences  //营业执照
            $scope.roadlicences=data[0].roadlicences;  //道路运输许可证
            $scope.headerpath=data[0].headerpath;  //头像
            $scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];

            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.$apply(element);
                if(scope.myScroll){
                    scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $scope.goBack = function(){
            $state.go('tab.myTransfer2',{inforid:inforid});
        }
        $scope.data=4;
        $scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];
    })
  /*  .controller('SearchCtrl',function($scope,$q){
        //$scope.tests = [{name:'西安'},{name:'南京'},{name:'上海'},{name:'广州'},{name:'哈尔滨'},{name:'西安'},{name:'南京'}];

        $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];


        $scope.onReload = function() {
            console.warn('reload');
            var deferred = $q.defer();
            setTimeout(function() {
                deferred.resolve(true);
            }, 1000);
            return deferred.promise;
        };
    })*/
    .controller('LoginCtrl',function($scope,$state,$window,$timeout,LoginService,AuthenticationService){

        /*$scope.$watch('user.isRemember',function(value){
            if(value){
                console.log(value);
            }
        });*/
        //alert(localStorage.getItem('token')+'   '+localData.getItem('tokens'));
        $scope.login = function(){
            LoginService.login($scope.user.phone,$scope.user.password)
                .success(function(data,status){
                    //alert(data.message+' sssss '+data.user.nickname);
                    /*if(data.message==false){
                        $scope.logInfo = '用户名或密码错误';
                        $timeout(function(){
                            $scope.logInfo = '';
                        },3000);
                        return;
                    }else if(data.message==true){
*/
                    /*if(data==false){
                        $scope.logInfo = '登录失败';
                        return;

                    }*/
                    AuthenticationService.isLogged = true;//认证成功
                    /*$window.sessionStorage.token = data.token;//保存token
                    $window.sessionStorage.user = JSON.stringify(data.user);*/
                    //localData.getItem('tokens',data.token);
                    localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    localStorage.setItem('token',data.token);
                    localStorage.setItem('user',JSON.stringify(data.user));

                    $state.go('/');
                    //}
                }).error(function (data,status) {
                    $scope.logInfo = '登录失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
    })
    .controller('ResetPassCtrl',function($scope,$state,$window,$timeout,$interval,LoginService,AuthenticationService){
        $scope.msgcode1='';
        $scope.user = {btnVal:' 获取验证码 '};

        $scope.logInfo='';
        $scope.getCode = function(){
            if(!isNaN($scope.user.btnVal)){
                return;
            }
            if($scope.user.phone==null||$scope.user.phone.length<11){
                $scope.logInfo = '请输入正确手机号码';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            if($scope.user.password==null||$scope.user.password.length<6){
                $scope.logInfo = '密码不能小于6位';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            LoginService.getCode($scope.user.phone,'resetPass')
                .success(function(data,status){
                    if(data=='nouser'){
                        return $scope.logInfo = '账号不存在！';

                    }else if(data=='err'){
                        return $scope.logInfo = '验证码获取失败！';
                    }

                    $scope.msgcode1=data;
                    $scope.user.btnVal=60;
                    var timer = $interval(function(){
                        $scope.user.btnVal-=1;
                        if($scope.user.btnVal==0){
                            $scope.user.btnVal='  重新获取  ';
                            $scope.msgcode1='';
                            $interval.cancel(timer);
                        }
                    },1000);

                }).error(function (data,status) {
                    $scope.logInfo = '获取验证码失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
        $scope.reset = function(){
            if($scope.user.msgcode!=$scope.msgcode1){
                $scope.logInfo = '验证码错误！';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }
            LoginService.resetPass($scope.user.phone,$scope.user.password)
                .success(function(data,status){
                    if(data.msg==true){
                        AuthenticationService.isLogged = false;
                        /*delete $window.sessionStorage.token;
                        delete $window.sessionStorage.user;*/
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        $state.go('login');
                    }

                }).error(function (data,status) {
                    $scope.logInfo = '重置失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }

    })
    .controller('RegisterCtrl',function($scope,$state,$window,$timeout,$interval,LoginService,AuthenticationService){
        $scope.msgcode1='';
        $scope.user = {btnVal:' 获取验证码 '};
        $scope.loginMsg='';
        $scope.lmsg = false;
        $scope.logInfo='';
        $scope.getCode = function(){
            if(!isNaN($scope.user.btnVal)){
                return;
            }
            if($scope.user.phone==null||$scope.user.phone.length<11){
                $scope.logInfo = '请输入正确手机号码';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            if($scope.user.password==null||$scope.user.password.length<6){
                $scope.logInfo = '密码不能小于6位';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }
            LoginService.getCode($scope.user.phone,'register')
                .success(function(data,status){
                    if(data=='hasuser'){
                        return $scope.logInfo = '账号已存在！';

                    }else if(data=='err'){
                        return $scope.logInfo = '验证码获取失败！';
                    }


                    $scope.msgcode1=data;
                    $scope.user.btnVal=60;
                    var timer = $interval(function(){
                        $scope.user.btnVal-=1;
                        if($scope.user.btnVal==0){
                            $scope.user.btnVal='  重新获取  ';
                            $scope.msgcode1='';
                            $interval.cancel(timer);
                        }
                    },1000);

                }).error(function (data,status) {
                    $scope.logInfo = '获取验证码失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
        $scope.register = function(){
            /*if($scope.user.msgcode!=$scope.msgcode1){
                $scope.logInfo = '验证码错误！';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }*/
            console.log('sssssss');
            LoginService.register($scope.user.phone,$scope.user.password)
                .success(function(data,status){
                    if(data.msg==true){
                        AuthenticationService.isLogged = false;
                        /*delete $window.sessionStorage.token;
                        delete $window.sessionStorage.user;*/
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        var countdown=5;
                        var dian='.'

                        /*$state.go('/');*/
                        LoginService.login($scope.user.phone,$scope.user.password)
                            .success(function(data,status){
                                AuthenticationService.isLogged = true;//认证成功
                                localStorage.setItem('token',data.token);
                                localStorage.setItem('user',JSON.stringify(data.user));
                                $scope.lmsg = true;
                                $scope.loginMsg = '自动登录'+dian+'  '+countdown;
                                countdown-=1;
                                dian+='.';
                                var time = $interval(function(){
                                    $scope.loginMsg = '自动登录'+dian+'  '+countdown;
                                    if(countdown == 0){
                                        $interval.cancel(time);
                                        $state.go('/');
                                    }
                                    countdown-=1;
                                    dian+='.';

                                },1000);

                            }).error(function (data,status) {
                                $scope.logInfo = '登录失败';
                                $timeout(function(){
                                    $scope.logInfo = '';
                                },3000);
                            });

                    }

                }).error(function (data,status) {
                    $scope.logInfo = '注册失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }

    })
    .controller('TabCtrl',function($scope,$state,$window,$location,$rootScope,LoginService){
        //alert('sssss');
       // document.getElementById('footer')
        $rootScope.num1;
        $rootScope.num2;
        $rootScope.num3;
        $rootScope.num4;
        if($location.$$url.indexOf('transfer')>-1){
            $rootScope.num1=1;

        }else if($location.$$url.indexOf('myTransfer')>-1){
            $rootScope.num2=1;

        }else if($location.$$url.indexOf('myOrders')>-1){
            $rootScope.num3=1;

        }else if($location.$$url.indexOf('center')>-1){
            $rootScope.num4=1;
        }

        $rootScope.setColor = function(index){
            setCo();
            changeCo(index);
            console.log('sss');
        }
        function setCo(){
            $rootScope.num1=2;
            $rootScope.num2=2;
            $rootScope.num3=2;
            $rootScope.num4=2;
        }

        function changeCo(index){
            switch (index){
                case 1:
                    $rootScope.num1=1;
                    break;
                case 2:
                    $rootScope.num2=1;
                    break;
                case 3:
                    $rootScope.num3=1;
                    break;
                case 4:
                    $rootScope.num4=1;
                    break;
            }

        }
    })
    .controller('CitysCtrl',function($scope,$state,$stateParams,TransferService){
        $scope.citys = TransferService.getCityList();
        $scope.allcitys = TransferService.getAllCitys();
        $scope.provinces = TransferService.getProvince();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        $scope.myScroll1 = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
            $scope.myScroll1.refresh();
        },500);
        $scope.goBack = function(){
            $state.go('tab.transfer');
        };
        $scope.selectCity = function(id,province,city){//判断上一页面传来的值是1则改变事发地点2为目的地
            //console.log(province+" "+city);
            if($stateParams.type==1){
                TransferService.getInforData().startCityId = id;
                TransferService.getInforData().startCity = province+" "+city;

            }else if($stateParams.type==2){
                TransferService.getInforData().endCityId = id;
                TransferService.getInforData().endCity = province+" "+city;
            }
            $state.go('tab.transfer');
        };

        $scope.selectProvince = function(province){
            var citys = [];
            for(var i=0;i<$scope.allcitys.length;i++){
                if(province==$scope.allcitys[i].province){
                    citys.push($scope.allcitys[i]);
                }
            }
            $scope.citys = citys;
            //this.style.backgroundColor=this.style.backgroundColor==''?'#a00':'';return false;
            /*$(this).css('color','#a00');*/
            setTimeout(function(){
                $scope.$apply();
                $scope.myScroll1.refresh();

            },500);
        }
    })
    .controller('TransferAddCarCtrl',function($scope,$state,$stateParams,$window,TransferService,CropperService){
        if(!TransferService.getCarbrandList().carbrand.length>0){
            TransferService.getCarbrands($scope);//查询汽车品牌
        }

        $scope.visible = true;
        $scope.color = 1;
        $scope.color1 = 2;
        $scope.toggle = function (t) {//显示隐藏零散车辆和整板车辆
            if(t==1){
                $scope.visible = true;
                $scope.color = 1;
                $scope.color1 = 2;
                $scope.inforData.type = 1;
                TransferService.getCurrenttab().state = false;
            }else{
                $scope.visible = false;
                $scope.color1 = 1;
                $scope.color = 2;
                $scope.inforData.type = 2;//设置发车类型
                TransferService.getCurrenttab().state = true;
            }
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.myScroll.refresh();
            },500);
        }

        $scope.inforData = TransferService.getInforData();
        $scope.currentcar = TransferService.getCurrentCar();//当前显示的品牌和型号
        $scope.currentcar.cropper = CropperService.getCropperdata()[0];
        $scope.currentcar.filepath = CropperService.getCropperdata()[0].filename;
        $scope.currentcar.filename = CropperService.getCropperdata()[0].filepath;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,tap:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        if(TransferService.getCurrenttab().state){//设置那个tab显示
            $scope.visible = false;
            $scope.color1 = 1;
            $scope.color = 2;
            $scope.inforData.type = 2;//设置发车类型
        }

        setTimeout(function(){//延迟绑定点击事件
            $scope.myScroll.refresh();
            $scope.up = document.getElementById('uploadImg');
            $scope.cl = document.getElementById('uploadfile');
            $scope.carbrand = document.getElementById('carbrand');
            $scope.carnum = document.getElementById('carnum');
            $scope.plusnum = document.getElementById('plusnum');
            $scope.minusnum = document.getElementById('minusnum');
            $scope.dray11 = document.getElementById('dray11');
            $scope.dray22 = document.getElementById('dray22');
            /*$scope.goback = document.getElementById('goback');*/
            /*$scope.cl.addEventListener('tap', function () {
                alert('dddddd');
            }, false);*/
            var element = document.getElementById("mytext");
            if("\v"=="v") {
                element.onpropertychange = webChange;
            }else{
                element.addEventListener("input",webChange,true);
            }
            function webChange(){
                var r = /^\+?[1-9][0-9]*$/;
                console.log(element.value);
                if(r.test(element.value)){
                    $scope.currentcar.carnumber=element.value;
                }else{
                    $scope.currentcar.carnumber = 1;
                    element.value="1";
                }
            }
            $scope.up.addEventListener('tap', function () {
                $state.go('tab.cropper',{scale1:4,scale2:3,width:640,height:480,urltype:'transfer'});
                //$('#uploadfile').click();//点击隐藏的文件上传按钮
            }, false);
            $scope.carbrand.addEventListener('tap', function () {

                $state.go('tab.getCarBrandList');
            }, false);
            $scope.carnum.addEventListener('tap', function () {
                /*alert('nnnnnnnn');*/
                $state.go('tab.getCarNumList');
            }, false);
            $scope.plusnum.addEventListener('tap', function () {
                $scope.currentcar.carnumber+=1;
                //$scope.inforData.carnumber+=1;
                $scope.$apply();
                //TransferService.getInforData().carnumber =  $scope.inforData.carnumber;
                console.log($scope.inforData.carnumber);
            }, false);
            $scope.minusnum.addEventListener('tap', function () {
                if($scope.currentcar.carnumber==1){
                    return;
                }
                $scope.currentcar.carnumber-=1;
                //$scope.inforData.carnumber-=1;
                $scope.$apply();
                //TransferService.getInforData().carnumber =  $scope.inforData.carnumber;
            }, false);
            /*$scope.goback.addEventListener('tap', function () {
             $state.go('tab.transfer');//返回到上一页
             }, false);*/
            $scope.dray11.addEventListener('tap', function () {
                $('#dray1').click();
            }, false);
            $scope.dray22.addEventListener('tap', function () {
                $('#dray2').click();
            }, false);
        },500);

        $scope.goBack = function(){
            $state.go('tab.transfer');
        };
        $scope.Carlist = function(){
            $state.go('tab.carlist');
        }
        $scope.goCropper = function(){
            $state.go('tab.cropper');
        }
        $scope.issave=true;

        $scope.savetransfer = function(){
            if($scope.inforData.username==''||$scope.inforData.phone==''){
                alert('请返回填写用户姓名和手机号码')
                return;
            }
            if(!$scope.issave){//判断保存状态，正在保存直接返回
               /* alert('ssss');*/
                return;
            }
            //零散车辆类型并且carnum大于0，不存在添加当前页面数据到数组
            if($scope.inforData.type==2){//整板车类型不需要把当前页面默认选中的值添加进来
                if($scope.inforData.draynum.length<1){
                   /* alert('您还没有添加板车');
                    return;*/
                    $scope.inforData.draynum.push($scope.dray.value);
                    if($scope.dray.value==12){
                        $scope.inforData.draytype[0]+=1;
                        $scope.dray.smallnum+=1;
                    }else{
                        $scope.inforData.draytype[1]+=1;
                        $scope.dray.bignum+=1;
                    }
                    $scope.dray.value = 12;
                }
                $scope.issave=false;
                TransferService.savetransfer()
                    .success(function(data,status){
                        $scope.issave=true;
                    if(data){

                        TransferService.resetInforData();
                        $scope.currentcar = TransferService.resetCurrentCar();
                        $state.go('tab.complete',{isOk:true});
                        //alert('发布成功');
                    }else{
                        $state.go('tab.complete',{isOk:false});
                    }
                }).error(function(data,status){
                        $state.go('tab.complete',{isOk:false});
                        $scope.issave=true;
                });
            }else if($scope.inforData.type==1){//&&$scope.inforData.carnum.length>0
                if($scope.currentcar.brand=='品牌'||$scope.currentcar.num=='型号'||$scope.currentcar.carnumber<=0){//||$scope.currentcar.filepath==''

                    if($scope.inforData.carnum.length<1){
                            return alert('请检查是否选择正确');
                        }
                }else{
                    $scope.inforData.carnum.push($scope.currentcar);
                }
                $scope.currentcar = TransferService.resetCurrentCar();
                $scope.issave=false;
                TransferService.savetransfer()
                    .success(function(data,status){
                        $scope.issave=true;
                        if(data){
                            CropperService.getCropperdata()[0]={
                                scale1:'',
                                scale2:'',
                                width:'',
                                height:'',
                                filename:'',
                                filepath:'上传照片，增加竞价积极性'
                            };
                            TransferService.resetInforData();//重置页面数据
                            $scope.currentcar = TransferService.resetCurrentCar();
                            $state.go('tab.complete',{isOk:true});
                            //alert('发布成功');
                        }else{
                            $state.go('tab.complete',{isOk:false});
                        }


                    }).error(function(data,status){
                        $scope.issave=true;
                        $state.go('tab.complete',{isOk:false});
                    });
            }

        };
        $scope.addNum=$scope.inforData.carnum.length;
        $scope.dray=TransferService.getDray();
        //var currentcar = $scope.currentcar;
        $scope.addCar = function(type){//添加车辆
            if(type==1){
                if($scope.currentcar.brand=='品牌'||$scope.currentcar.num=='型号'||$scope.currentcar.carnumber<=0){//||$scope.currentcar.filepath==''

                    alert('请检查是否选择正确');
                    return false;
                }
                $scope.inforData.carnum.push($scope.currentcar);
                $scope.addNum=$scope.inforData.carnum.length;
                CropperService.getCropperdata()[0]={
                    scale1:'',
                    scale2:'',
                    width:'',
                    height:'',
                    filename:'',
                    filepath:'上传照片，增加竞价积极性'
                };
            }else{
               $scope.inforData.draynum.push($scope.dray.value);
                $scope.addNum=$scope.inforData.draynum.length;
                if($scope.dray.value==12){
                    $scope.inforData.draytype[0]+=1;
                    $scope.dray.smallnum+=1;
                }else{
                    $scope.inforData.draytype[1]+=1;
                    $scope.dray.bignum+=1;
                }

            }

            //currentcar = null;
            $scope.currentcar = TransferService.resetCurrentCar();
            $scope.dray.value = 12;
            return true;
        };


        /*$scope.selectCarbrand = function(){
            $state.go('tab.getCarBrandList');
        }*/

        $('#uploadfile').bind('change',function(){//jquery监听隐藏文本框值变化

            var fd = new FormData();
            fd.append("name", "车辆图片");
            fd.append("files", document.getElementById("uploadfile").files[0]);

            $scope.currentcar.filename = '';
            $scope.$apply();

            var xhr = new XMLHttpRequest();
            xhr.open("POST" ,"/uploadFiles" , true);
            xhr.setRequestHeader('Authorization','Bearer ' +  localStorage.getItem('token'))//$window.sessionStorage.token
            xhr.upload.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    document.getElementById('progress').innerHTML = '已上传 '+percentComplete.toString() + '%';
                }


            }, false);
            xhr.send(fd);
            xhr.onload = function(e) {
                if (this.status == 200) {
                    //$scope.inforData.fileName = this.responseText;
                    $scope.addNum=$scope.inforData.carnum.length;
                    document.getElementById('progress').innerHTML = '';
                    $scope.currentcar.filepath = this.responseText;
                    $scope.currentcar.filename = this.responseText.substring(0,10)+'.jpg';
                    $scope.$apply();
                }
            };

        });

    })
    .controller('CarBrandListCtrl',function($scope,$state,$stateParams,$location,TransferService){

        $scope.carbrands = TransferService.getCarbrandList().carbrand;
console.log($scope.carbrands)
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        $scope.myScroll1 = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll

        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
            $scope.myScroll1.refresh();
        },500);
        $scope.goTo = function (id) {
            $location.hash(id);
            //$anchorScroll();
            $scope.myScroll.refresh();
        }
        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.selectCarbrand = function(id,brand){
            TransferService.getCurrentCar().brand = brand;
            TransferService.getCurrentCar().bid = id;
            /*TransferService.getInforData().carnum.push(id);*/
            /*TransferService.getInforData().carbrand = brand;
            TransferService.getInforData().carbrandid = id;*/
            //选定车牌后请求对应型号
            TransferService.getCurrentCar().num='型号';
            TransferService.getCarbrandList().carnums=[];
            TransferService.getCarNumList(id);

            $state.go('tab.transferAddCar');
        }

    })
    .controller('CarNumListCtrl',function($scope,$state,$stateParams,TransferService){

        $scope.carnums = TransferService.getCarbrandList().carnums;//TransferService.getCarNums();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
        },500);

        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.selectCarnum = function(id,num){
            TransferService.getCurrentCar().num = num;
            TransferService.getCurrentCar().nid = id;
            //TransferService.getInforData().carnum.push(id);
            /*TransferService.getInforData().carnumid = id;*/
            $state.go('tab.transferAddCar');
        }

    })
    .controller('CarListCtrl',function($scope,$state,$stateParams,TransferService){

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);


        $scope.inforData = TransferService.getInforData();
        $scope.type = $scope.inforData.type;
        if($scope.type==1){
            $scope.carnum = $scope.inforData.carnum;//获取车辆数组
            TransferService.getCurrenttab().state = false;//设置零散车辆为默认显示的页面
        }else{
            TransferService.getCurrenttab().state = true;

            $scope.draylsit=[];
            $scope.draynum = $scope.inforData.draynum;
            for(var i=0;i<$scope.draynum.length;i++){
                if($scope.draynum[i]==12){
                    $scope.draylsit.push({type:'小板',num:12});
                }else{
                    $scope.draylsit.push({type:'大板',num:24});
                }
            }
        }
        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.pop1 = false;
        var index;
        $scope.confirm = function(idx){
            $scope.pop1 = true;
            index = idx;
        }
        $scope.delSelect = function(){

           /* if(!confirm("确定要删除此项吗？")){
                return;
            }*/
            if($scope.type==1){
                $scope.carnum.splice(index,1);//删除选中的元素
            }else{
                //alert(index);
                if($scope.draylsit[index].num==12){
                    TransferService.getDray().smallnum-=1;
                    TransferService.getInforData().draytype[0]-=1;
                }else{
                    TransferService.getDray().bignum-=1;
                    TransferService.getInforData().draytype[1]-=1;
                }
                $scope.draynum.splice(index,1);
                $scope.draylsit.splice(index,1);


            }
            $scope.pop1 = false;
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },300);

    })
    .controller('CompleteCtrl',function($scope,$state,$stateParams,$interval){
        $scope.isOk = $stateParams.isOk;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.times=3;
        var timer = $interval(function(){
            $scope.times-=1;
            if($scope.times==0){
                $scope.times= 0;
                $interval.cancel(timer);
                $state.go('tab.myTransfer',{random:'update'});
            }
        },1000);


        $scope.goBack = function(){
            $state.go('tab.transfer');
        };

    })
    .controller('CompleteCtrlQuo',function($scope,$state,$stateParams,$interval){
        $scope.isOk = $stateParams.isOk;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.times=3;
        var timer = $interval(function(){
            $scope.times-=1;
            if($scope.times==0){
                $scope.times= 0;
                $interval.cancel(timer);
                $state.go('tab.myOrders');
            }
        },1000);
        $scope.goBack = function(){
            $state.go('tab.myTransfer',{random:'update'});
        };

    })
    .controller('CropperCtrl',function($scope,$state,$stateParams){
        $scope.scale1 = $stateParams.scale1;
        $scope.scale2 = $stateParams.scale2;
        $scope.width = $stateParams.width;
        $scope.height = $stateParams.height;
        $scope.urltype = $stateParams.urltype;
        $scope.goBack = function(){
            if($stateParams.urltype=='transfer'){//判断哪个页面进来的，回到哪个页面
                $state.go('tab.transferAddCar');
            }else if($stateParams.urltype == 'upheader'){
                $state.go('tab.center');
            }

        };



    });

;/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.orderControllers', ['ui.router'])
    .config(function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state('tab.orderDetail' ,{
                url:'/myOrders/orderdetail',
                templateUrl:'view/order/order-detail.html',
                controller:'OrderDetailCtrl'
                ,access: { requiredLogin: true }
            })
            .state('tab.orderComment' ,{
                url:'/myOrders/ordercomment',
                templateUrl:'view/order/order-comment.html',
                controller:'OrderCommentCtrl'
                ,access: { requiredLogin: true }
            })
            .state('tab.orderCars' ,{
                url:'/myOrders/ordercars'
                ,templateUrl:'view/order/order-cars.html'
                ,controller:'OrderCarsCtrl'
                ,access: { requiredLogin: true }
            })
    })
    .filter('dateFormat' ,function(){
        return function(input){
            if(typeof input == 'string'){
                return input.substring(0 ,10);
            }
        }
    })
    .filter('orderState' ,function(){
        return function(input){
            switch (input){
                case 5:return '已取消';
                case 2:return '已接受';
                case 3:return '已评价';
            }
        }
    })
    .controller('MyOrderCtrl',function($scope,$rootScope,$state,$http ,OrderService){
        /*$scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);*/
        $('#order-wrapper').css('min-height',$(window).height()-135+'px');


        $scope.switch = OrderService.switch;
        var order = $scope.orders = OrderService.orders();//重新打开我的订单页面时，从OrderService初始化数据
        if($rootScope.refreshOrder){
            order[0] = order[1] = [];
            $rootScope.refreshOrder = false;
        }
        /*if(order[$scope.switch].length == 0){

            loadOrder();
        }else{
            setTimeout(function(){
                refreshScroll();
            },300);
        }*/

        pull($scope,"wrapper",function(pull){
            if(OrderService.busy)return;
            if('pullDown'==pull) {//下拉刷新
                loadOrder();
            }else{//上拉加载更多
                moreOrder();
            }
        });

        //切换订单tab选项
        $scope.switchOrders = function(idx){
            //$scope.myScroll.scrollTo(0, - $scope.pullDownOffset,0);
            $scope.switch = OrderService.switch = idx;
            $('.noorder').hide();
            if(idx==0){
                $('.order1').hide();
                $('.order0').show();
            }else{
                $('.order0').hide();
                $('.order1').show();
            }
            refreshScroll();
            if(order[$scope.switch].length==0){
                loadOrder();
            }
        }
        $scope.switchOrders($scope.switch);

        //跳转到订单详情页
        $scope.goDetail = function(idx){
            OrderService.setIdx(idx);
            $state.go('tab.orderDetail');
            //$scope.count++;
        }


        var config = {
            timeout:8000
        }
        $scope.noOrders = OrderService.noOrders;
        $scope.noMore = false;
        function loadOrder(){
            OrderService.busy = true;

            var params = OrderService.param();
            var page = params.page;//如果加载失败，恢复之前的页数
            params.page = 1;
            $http.post('/users/myorders' ,params ,config)
                .success(function(data,status) {
                    if(data.err){
                        params.page = page;
                    }else{
                        if(data.total == 0){
                            //$scope.noOrders[$scope.switch] = true;
                            $('.noorder').show();
                        }else{
                            //$scope.noOrders[$scope.switch] = false;
                            $('.noorder').hide();
                        }
                        truncateOrder(data.rows);
                        OrderService.putOrder(data );
                        //$scope.$apply();

                        refreshScroll();
                    }
                    OrderService.busy = false;

                })
                .error(function (data,status) {
                    params.page = page;
                    OrderService.busy = false;
                });

        }
        function moreOrder(){
            var status = OrderService.status();
            /*if(status.total == status.length){//所有数据都已被加载
             return;
             }*/
            if(!$scope.orders[$scope.switch].length){//如果没有数据，加载第一页
                loadOrder();
                return;
            }
            var params = OrderService.param();
            params.page += 1;
            OrderService.busy = true;
            $http.post('/users/myorders' ,params ,config)
                .success(function(data) {
                    if(data.err){
                        params.page -= 1;
                    }else{
                        if(data.rows.length == 0){
                            //var wHeight = screen.clientHeight;
                            //document.getElementById('noMore').style.top = wHeight - 100 + 'px';
                            document.getElementById('noMore').style.display = 'block';
                            setTimeout(function () {
                                document.getElementById('noMore').style.display = 'none';
                            } ,2000)
                        }
                        truncateOrder(data.rows);
                        OrderService.appendOrder(data );
                        //$scope.$apply();
                    }
                    OrderService.busy = false;

                    refreshScroll();

                })
                .error(function (data,status) {//alert(status);
                    params.page -= 1;
                    OrderService.busy = false;

                });
        }

        function truncateOrder(rows){
            var rs = rows;
            for(var x in rs){
                var i = rs[x];
                if(i.type == 1){
                    var carnums = i.carnum.split(',');
                    i.carnums = carnums;
                    var nums = i.num.split(',');
                    var totalnum = 0;
                    for(var xx in nums){
                        nums[xx] = Number(nums[xx]);
                        totalnum += nums[xx];
                    }
                    i.nums = nums;
                    i.total = totalnum;
                    i.note = '本次共运送 '+carnums.length+'种型号共 '+totalnum+'辆车';
                }else if(i.type == 2){
                    i.nums =  i.carnum.split(',');
                    i.nums[0] = Number(i.nums[0])
                    i.nums[1] = Number(i.nums[1])
                    i.note = '本次共运送 ';
                    if(i.nums[0]){
                        i.note += '小板'+i.nums[0] + '板 ';
                    }
                    if(i.nums[1]){
                        i.note += '大板'+i.nums[1] + '板';
                    }
                }
            }

        }

        function refreshScroll(){
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                //$scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },300);
        }
    })
    .controller('OrderDetailCtrl' ,function($scope ,$state ,$http ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var order = OrderService.get();
        $http.post('/users/orderdetail' ,{id:order.id})
            .success(function(data){
                if(data.err){

                }else{
                    /*var oldDetail = OrderService.orderDetail;
                    if(oldDetail && data.id != oldDetail.id){
                        OrderService.comment = null;//清空之前做的评论数据
                    }*/
                    OrderService.set(data);
                    order = OrderService.orderDetail = $scope.order = data;

                    setTimeout(function(){
                        $scope.myScroll.refresh();
                    },600);
                }
            })
            .error(function(data){

            })

        var busy = false;
        $scope.cancel = function(){
            if(busy || order.status != 2)return;
            busy = true;
            if(!confirm('确定取消该订单吗？')){
                setTimeout(function(){busy=false;},200)
                return;
            }
            $http.post('/users/cancelorder' ,{id:$scope.order.id})
                .success(function(data){
                    if(data.err){
                        alert('网络连接出错，请稍候再试')
                    }else{
                        $rootScope.refreshOrder = true;
                        order.status = 5;
                        alert('订单取消成功！')
                    }
                    busy = false;
                })
                .error(function(data){
                    busy = false;
                })
        }

        $scope.go = function(state){
            $state.go(state);
        }
        $scope.goComment = function(){
            if(order.status == 5)return;
            $state.go('tab.orderComment');
        }

    })
    .controller('OrderCarsCtrl' ,function($scope ,$state ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var order = $scope.order = OrderService.orderDetail;
        var cars = $scope.cars = order.cars;
        if(order.type==1){
            $scope.orderCount = order.total + '辆车';
        }else{
            $scope.types = [];
            var cc = '';
            if(order.carnums[0]){
                cc += order.carnums[0]+'个小板';
                $scope.types.push({type:'小板',num:order.carnums[0]})
            }
            if(order.carnums[1]){
                cc += order.carnums[1]+'个大板';
                $scope.types.push({type:'大板',num:order.carnums[1]})
            }
            $scope.orderCount = cc;
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);
    })
    .controller('OrderCommentCtrl' ,function($scope ,$rootScope,$state ,$http ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var order = OrderService.orderDetail;
        var carrier = $scope.carrier = OrderService.orderDetail.carrier;

        $scope.flag = order.status == 3;
        if($scope.flag){
            $scope.comment = order.comment;
            document.getElementById('commentText').disabled = true;
        }else{
            var comment = OrderService.comment;
            if(comment && comment.inforid == order.id){
                $scope.comment = comment;
            }else{
                OrderService.comment = $scope.comment = {
                    attitude:0
                    ,care:0
                    ,corresponds:0
                    ,evaluation:''
                    ,inforid:order.id
                    ,userid:order.user.id
                    ,carrierid:carrier.id
                }
            };
        }
        $scope.authImg = (carrier.authstate == 0 ? 'icon-icon-19' : 'icon-icon-18');
        $scope.authText = (carrier.authstate == 0 ? '未认证' : '已认证');
        $scope.postText = $scope.flag?'已 评 价':'评 价';


        //评价打分
        $scope.graderArray = [1,2,3,4,5];
        $scope.grade = function(t ,idx){
            if($scope.flag)return;
            $scope.comment[t] = idx +1;
        }
        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);
        //
        $scope.go = function(state){
            $state.go(state);
        }
        //提交评论
        $scope.post = function(){
            if($scope.flag)return;
            if(!($scope.comment.attitude && $scope.comment.care && $scope.comment.corresponds && $scope.comment.evaluation)){
                alert('请输入完整评价');
                return;
            }
            $http.post('/users/comment' ,{commentJSON:JSON.stringify($scope.comment)})
                .success(function(data){
                    if(data.err){
                        alert('评价失败，请稍候再试！')
                    }else{
                        $rootScope.refreshOrder = true;
                        $scope.flag = true;
                        OrderService.orderDetail.status = 3;
                        OrderService.orderDetail.comment = $scope.comment;
                        document.getElementById('commentText').disabled = true;
                        alert('评价成功！')
                    }
                })
                .error(function(data){

                })
        }
    });;/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.centerControllers', ['ui.router'])
    .config(function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state('tab.mySuggest' ,{
                url:'/center/mysuggest',
                templateUrl:'view/center/mysuggest.html',
                controller:'SuggestCtrl'
                ,access: { requiredLogin: true }
            })
            .state('tab.myAuth' ,{
                url:'/center/myauth',
                templateUrl:'view/center/auth.html',
                controller:'MyAuthCtrl'
                ,access: { requiredLogin: true }
            })
            .state('tab.myInfo' ,{
                url:'/center/myinfo',
                templateUrl:'view/center/myinfo.html',
                controller:'MyInfoCtrl'
                ,access: { requiredLogin: true }
            })
    })
    .filter('authPostFilter' ,function(){
        return function(input){
            switch (input){
                case 0:return '申 请 认 证';
                case 1:return '已 认 证';
                case 2:return '等 待 审 核'
            }
        }
    })
    .controller('CenterCtrl',function($scope ,$http ,$rootScope ,$state ,CenterService ,AuthenticationService){

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.other=true;
        if(localStorage.isOther=='false'){
            $scope.other=false;
        }
        $scope.logout = function(){
            AuthenticationService.isLogged = false;
            /*delete $window.sessionStorage.token;
             delete $window.sessionStorage.user;*/
            /* window.localStorage.setItem('token',data.token);
             window.localStorage.setItem('user',JSON.stringify(data.user));*/
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            $state.go('/')
        }
        if(!localStorage.user){
            AuthenticationService.isLogged = false;
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            $state.go('/')
        }

        if(JSON.parse(localStorage.user)){
            /*更新认证状态*/
            var user = $scope.user = JSON.parse(localStorage.user);
            CenterService.getAuthState(user.id).success(function(data,status) {
                $scope.user.authstate = data.state.authstate;
            });

            var info = $scope.info = {
                id:user.id
                ,nickname:user.nickname
                ,name:user.name
                ,address:user.address
                ,introduce:user.introduce
                ,phone:user.phone
            }

        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);

        $scope.go = function(state){
            $state.go(state);
        }
        $scope.goModifyFace = function(){
            $state.go('tab.cropper',{scale1:1,scale2:1,width:500,height:500,urltype:'upheader'});
        }

        $scope.save =function(idx){
            var Regx = /[A-Za-z][0-9]|[0-9][A-Za-z]|[A-Za-z]/;

            if(info.address==null||info.address==''||info.address.replace(/^[0-9]*$/,'1')==1){
                toast('请正确填写地址');
            }else if(Regx.test(info.address)) {
                toast('请正确填写地址');

            }/*else if(info.name==null||info.name==''||info.name.replace(/^[0-9]*$/,'1')==1){
                toast('请正确填写姓名');
            }*/else if(info.nickname==null||info.nickname==''||info.nickname.replace(/^[0-9]*$/,'1')==1){
                toast('请正确填写昵称');
            }else {
                //var p = phoneEle.value;
                //info.phone=p;
                console.log(info.phone+"----------")
                $http.post('/users/modifyinfo', {infoJSON: JSON.stringify(info)})
                    .success(function (data) {
                        if (data.err) {

                        } else {
                            toast('保存成功')
                            document.getElementById('info-nickname').blur();
                            //document.getElementById('info-name').blur();
                            document.getElementById('info-address').blur();
                            document.getElementById('info-introduce').blur();
                            user.nickname = info.nickname;
                            //user.name = info.name;
                            user.address = info.address;
                            user.introduce = info.introduce;
                            user.phone = info.phone;
                            localStorage.user = JSON.stringify(user);
                        }
                    })
            }
        }

        //修改手机
        $scope.modifyPhone = function(){
            resume();
            var option = {
                ele:pop
                ,onClose:function(){
                    if(state!=3){
                        if(confirm('操作还没有完成，确定取消吗？')){
                            if(state == 2){
                                phoneEle.value = '';
                            }
                        } else{
                            return false;
                        }
                    }else{
                        state = 2;
                    }
                    codeEle.value = '';
                    code = '';
                    timing = 59;
                    return true;
                }
            }
            popWin(option);
        }
        var pop = document.getElementById('phone-popup');
        var phoneEle = document.getElementById('info-phone');
        var msgEle = document.getElementById('get-msg');
        var msgEle1 = document.getElementById('get-msg1');
        var codeEle = document.getElementById('info-code');
        var err = document.getElementById('phone-error');
        var timeEle = document.getElementById('timing');

        phoneEle.value = user.phone;
        var msging = false;
        var state = 1;
        var msg = '您正在验证您的登录手机号'+user.phone+',验证码为:$$【运车管家】';
        var data = null;
        var code = '';
        var timing = 0;
        msgEle.addEventListener('click' ,function(){
            var p = phoneEle.value.replace(/(^\s*)|(\s*$)/g, "");
            if(p.length != 11){
                //err.innerHTML = '<span style="color:#F74042;">手机号格式不正确</span>';
                showErr('手机号格式不正确')
                phoneEle.focus();
                return;
            }
            if(state == 1){
                data = {
                    username:user.phone
                    ,type:'sendold'
                }
            }else{
                data = {
                    username:p
                    ,type:'modifyphone'
                }
            }
            $http.post('/users/getCode' ,data ,{timeout:8000})
                .success(function(data){
                    if(data=='hasuser'){
                        //err.innerHTML = '<span style="color:#F74042;">该手机号已经被注册</span>'
                        showErr('该手机号已经被注册')
                    }else{
                        //err.innerHTML = data;
                        code = data;
                        console.log(code);
                        showMsg('请输入验证码')
                        //计时器
                        timing = 0;
                        msgEle.style.display = 'none';
                        msgEle1.style.display = 'block';
                        var timer = setInterval(function(){
                            timing ++;
                            timeEle.innerText = 60 - timing ;
                            if(timing >= 60){
                                timing = 0;
                                clearInterval(timer);
                                msgEle.style.display = 'block';
                                msgEle1.style.display = 'none';
                            }
                        } ,1000)
                    }
                })
                .error(function(){

                })
            //code = '111111';showMsg('请输入验证码')

        })
        codeEle.addEventListener('input' ,function(){
            resume(' ');
            if(!code){
                showMsg('请点击获取验证码');
                return;
            }
            var c = codeEle.value;//alert(c);
            if(c.length < 6){
                return;
            }
            if(c!=code){
                showErr('验证码不正确');
            }else{
                timing = 59;
                if(state == 1){
                    code = '';
                    state = 2;
                    //err.innerHTML = '<span style="color:dodgerblue;">验证码正确，请输入新手机号码</span>';
                    resume();
                    phoneEle.disabled = false;
                    phoneEle.value = '';
                    codeEle.value = '';
                }else{
                    //err.innerHTML = '<span style="color:dodgerblue;">验证码正确，请稍等...</span>';
                    showSave();
                    /*var p = phoneEle.value;
                    data = {
                        id:user.id
                        ,phone:p
                    }
                    $http.post('/users/modifyinfo' ,{infoJSON:JSON.stringify(data)})
                        .success(function(data){
                            if(data.err){

                            }else{
                                state = 3;
                                err.innerHTML='<span style="color:dodgerblue;">手机号已经修改成功</span>';
                                user.phone = p;
                                localStorage.user = JSON.stringify(user);
                                $scope.$apply();
                            }
                        })*/
                }
            }
        })
        phoneEle.addEventListener('input' ,function(){
            //err.innerHTML = '';
            resume();
            code = '';
        })
        function showErr(msg){
            err.innerText = msg;
            err.className = 'phone-error err';
        }
        function showMsg(msg){
            err.innerText = msg;
            err.className = 'phone-error';
        }
        function showSave(){
            err.innerText = '提 交';
            err.className = 'phone-error save';
            err.addEventListener('click' ,savePhone);
        }
        function resume(msg){
            //err.removeEventListener('click' ,savePhone);
            err.className = 'phone-error';
            if(state == 1){
                err.innerText = msg || '请先验证原手机号码';
            }else{
                err.innerText = msg || '请输入您的新手机号码';
            }
        }
        function savePhone(){
            var c = codeEle.value;
            if(!code || c!= code){
                return;
            }
            var ph = phoneEle.value;
            console.log(ph);
            info.phone = ph;
            state = 3;
            resume('验证码正确');
            $scope.user.phone=info.phone;
            //$http.post('/users/modifyinfo' ,{infoJSON:JSON.stringify(data)})
            //    .success(function(data){
            //        if(data.err){
            //
            //        }else{
            //            state = 3;
            //            resume('手机号已经修改成功');
            //
            //            localStorage.user = JSON.stringify(user);
            //            //$scope.$apply();
            //        }
            //    })
        }

        pop.parentNode.removeChild(pop)
        //popWin(pop)
    })
    .controller('MyAuthCtrl',function($scope ,$rootScope , CenterService ){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,tap:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var user = $scope.user = JSON.parse(localStorage.user);

        var auth = $scope.auth = CenterService.auth;
        if(user.authstate == 2 || user.authstate==1){
            auth = $scope.auth = CenterService.auth = {
                name:user.name
                ,idnum:user.idcard
                ,idTip:user.idTip
            }
            /*document.getElementById('auth-name').disabled = true;
            document.getElementById('auth-idnum').disabled = true;
            document.getElementById('auth-id').disabled = true;*/
        }else{
            if(auth){
                auth.name = auth.name || user.name;
            }
            if(!(auth && auth.id==user.id)){
                auth = $scope.auth = CenterService.auth = {
                    id :user.id
                    ,name:user.name
                    ,idnum:''
                    ,idcard:null
                    ,idTip:''
                }
            }
        }


        var tip = '上传身份证图片';
        var idFile = document.getElementById('auth-id')
        document.getElementById('auth-id-btn').addEventListener('tap' ,function(e){
            idFile.click()
        } ,false);
        idFile.addEventListener('change' ,function(){
            auth.idcard = idFile.files[0];
            var v = this.value;
            if(v){
                v = v.substring(v.lastIndexOf('\\')+1);
            }
            auth.idTip = v || tip;
            $scope.$apply();
        });

        //提交认证表单
        $scope.busy = false;
        var idReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        document.getElementById('auth-post').addEventListener('tap' ,function(){
            if(user.authstate == 1 || $scope.busy)return;
            if(!auth.name){//用户名必填
                toast('请输入用户名');
                document.getElementById('auth-name').focus();
                return;
            }
            if(!idReg.test(auth.idnum)){
                toast('身份证号码格式不正确，需要15位或18位');
                document.getElementById('auth-idnum').focus();
                return;
            }
            if(!auth.idcard){
                toast('请选择身份证图片');
                return;
            }
            var data = new FormData();
            data.append('id' ,user.id);
            data.append('name' ,auth.name);
            data.append('idnum' ,auth.idnum);
            data.append('idcard' ,auth.idcard);
            var params = {
                data:data
                ,url:'/users/auth'
            }
            CenterService.postFileForm(params ,$scope ,function(data){
                if(!data.err){
                    //alert('资料已上传，请等待人工审核');
                    $scope.busy = false;
                    user.authstate = 2;
                    user.name = auth.name;
                    user.idcard = auth.idnum;
                    user.idTip = auth.idTip;
                    $scope.$apply();
                    localStorage.user = JSON.stringify(user);
                    /*document.getElementById('auth-name').disabled = true;
                    document.getElementById('auth-idnum').disabled = true;
                    document.getElementById('auth-id').disabled = true;*/
                }
            })
        })

        $scope.error = '';
        $scope.loadingTip = '';
        function toast(msg){
            $scope.error = msg;
            $scope.$apply();
            setTimeout(function(){
                $scope.error = '';
                $scope.$apply();
            } ,3000)
        }

        //首次加载页面，刷新iScroll
        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);
    })
    .controller('MyInfoCtrl',function($scope ,$http ,CenterService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);


        var user =  $scope.user = JSON.parse(localStorage.user);
        var info = $scope.info = CenterService.info;
        if(!(info && info.id==user.id)){
            info = $scope.info = CenterService.info = {
                id:user.id
                ,nickname:user.nickname
                ,address:user.address
                ,introduce:user.introduce
            }
        }else{
            info.nickname = info.nickname || user.nickname;
            info.address = info.address || user.address;
            info.introduce = info.introduce || user.introduce;
        }

        $scope.post = function(){
            if(!(info.nickname && info.address && info.introduce)){
                return;
            }
            $http.post('/users/modifyinfo' ,{infoJSON:JSON.stringify(info)})
                .success(function(data){
                    if(data.err){
                        alert('网络连接失败，请稍候再试')
                    }else{
                        user.nickname = info.nickname;
                        user.address = info.address;
                        user.introduce = info.introduce;
                        localStorage.user = JSON.stringify(user);
                        alert('已经保存成功')
                    }
                })
        }
    })
    .controller('SuggestCtrl' ,function($scope ,$http ,CenterService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var user = $scope.user = JSON.parse(localStorage.user);
        var suggest = $scope.suggest = CenterService.suggest;
        if(!(suggest&&suggest.userid==user.id)){
            suggest = CenterService.suggest = $scope.suggest = {
                userid:user.id
                ,content:''
            }
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);

        $scope.post = function(){
            //suggest.content = suggest.content.replace(/(^\s*)|(\s*$)/g, "");
            document.getElementById('suggest-content').value = suggest.content;
            if(!suggest.content){
                document.getElementById('suggest-content').focus();
                return;
            }
            $http.post('/users/suggest' ,{suggestJSON:JSON.stringify(suggest)})
                .success(function(data){
                    if(data.err){
                        alert('网络连接出错，请稍候再试')
                    }else{
                        alert('建议已经提交成功！')
                        suggest.content = '';
                    }
                })
        }
    });


function popWin(option){
    var ele = option.ele;
    var wHeight = window.innerHeight;
    var wWidth = window.innerWidth;
    var wrapper = document.createElement("div");
    document.body.appendChild(wrapper);
    wrapper.style.position = 'fixed';
    wrapper.style.top = 0;
    wrapper.style.left = 0;
    wrapper.style.width = wWidth+'px';
    wrapper.style.height = wHeight+100+'px';
    wrapper.style.background = 'rgba(100,100,100,0)';
    wrapper.style.zIndex = 9999;
    var inner = document.createElement("div");
    wrapper.appendChild(inner);
    inner.appendChild(ele);
    var top = wHeight*0.5 - ele.offsetHeight*0.7 ;
    if(top < 60){
        top = 60;
    }
    var left = wWidth*0.5 - ele.offsetWidth*0.5 ;
    inner.style.position = 'absolute';
    inner.style.top = top+'px';
    inner.style.left = left+'px';
    var btnClose = document.createElement('div');
    inner.appendChild(btnClose);
    btnClose.style.position = 'absolute';
    btnClose.style.top = '-4px';
    btnClose.style.right = '-4px';
    btnClose.innerText = "×";
    btnClose.style.fontSize = '16px';
    btnClose.style.lineHeight = '1';
    btnClose.style.borderRadius = '50%';
    btnClose.style.padding = '2px 5px';
    btnClose.style.color = 'white';
    btnClose.style.background = '#666';

    btnClose.addEventListener('click' ,function(e){
        if(!option.onClose()){
            return;
        }
        document.body.removeChild(wrapper);
    })
};/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.services', [])
    .factory('MainService',function(){
        return {
            all: function() {
                return null;
            },
            get: function() {
                // Simple index lookup
                return null;
            }
        }
    })
    .factory('LoginService',function($http){
        return {
            login: function(phone,password) {
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/users/login',
                    data:{
                        username:phone,
                        password:password
                    }
                });
            },
            getCode: function(phone,type) {
                // Simple index lookup
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/users/getCode',
                    data:{
                        username:phone,
                        type:type
                    }
                });
            },
            resetPass:function(phone,password) {
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/users/resetPass',
                    data:{
                        username:phone,
                        password:password
                    }
                });
            },
            register:function(phone,password) {
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/users/register',
                    data:{
                        username:phone,
                        password:password,
                        type:1

                    }
                });
            },
            accept:function(phone,name,myphone) {
                console.log(phone+"======="+name+"========"+myphone);
                if(name){
                    return $http({ //返回promise对象
                        method:'POST',
                        url:'/users/Accept',
                        data:{
                            phone:phone,
                            name:name,
                            myphone:myphone
                        }
                    });
                }else{
                    return $http({ //返回promise对象
                        method:'POST',
                        url:'/users/Accept',
                        data:{
                            phone:phone,
                            name:false,
                            myphone:myphone
                        }
                    });
                }

            }
        }
    })
    .factory('TransferService',function($http){
        var date = new Date();
        var month = date.getMonth()+1;
        var day = date.getDate();
        if(month<10){
            month = '-0'+month;
        }else{
            month = '-'+month
        }
        if(day<10){
            day = '-0'+day;
        }else{
            day = '-'+day;
        }
        var dd = date.getFullYear()+month+day;
        var userphone='';
        if(localStorage.getItem('user')){
            userphone = Number(JSON.parse(localStorage.getItem('user')).phone)
        }

        var inforData = {
            type:1,//默认零散数量//2整板
            startCity:'',
            endCity:'',
            startCityId:'',
            endCityId:'',
            startTime:dd,
            endTime:dd,
            username:'',
            phone:userphone,
            /*carbrand:[],
            carbrandid:'',*/
            carnum:[],
            draynum:[],
            draytype:[0,0]
            //carnumid:'',
            //fileName:[]/*,
            //carnumber:[]//汽车数量*/
        };

        var carbrand={carbrand:[],carnums:[]};
        var carnums=[];

        var citys = [];
        var allcitys = [];
        var province = [];
        var currentcar = {brand:'品牌',bid:'',num:'型号',nid:'',carnumber:1,filepath:'',filename:'上传照片，增加竞价积极性'};
        /*var citys = */
        var currenttab = {state:false};
        var dray = {value:'12',bignum:0,smallnum:0};
        return {
            getCitys:function($scope){
                $http({
                    method:'GET',
                    url:'/getCityList',
                    data:{
                    }
                }).success(function(data,status){
                    allcitys = data;
                    for(var i=0;i<data.length;i++){
                        if($.inArray(data[i].province,province)==-1){
                            province.push(data[i].province);
                        }

                    }
                    for(var i=0;i<data.length;i++){
                        if(province[0]==data[i].province){
                            citys.push(data[i]);
                        }
                    }

                    inforData.startCity='北京市 朝阳';//设置默认城市
                    inforData.startCityId=20;
                    inforData.endCity='山东 济南';
                    inforData.endCityId=253;


                    $scope.inforData = inforData;
                    setTimeout(function(){//因为有冲突等会执行scope.$apply();
                        $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                    },500);
                }).error(function(data,status){

                });
            },
            getCarbrands:function($scope){
                $http({
                    method:'GET',
                    url:'/getCarBrandList',
                    data:{
                    }
                }).success(function(data,status){
                    $scope.carbrands = data;
                    carbrand.carbrand = data;
                    setTimeout(function(){
                        $scope.myScroll.refresh();
                    },500);
                }).error(function(data,status){

                });
            },
            getCarNumList:function(id){
                $http({
                    method:'GET',
                    url:'/getCarNumList?id='+id,
                    data:{
                    }
                }).success(function(data,status){
                    carbrand.carnums = data;//车型列表

                }).error(function(data,status){

                });
            },
            savetransfer:function(){
                return $http({
                    method:'POST',
                    url:'/savetransfer',
                    data:{
                        inforData:inforData
                    }
                });
            },
            getCityList:function(){
              return citys;
            },
            getProvince:function(){
                return province;
            },
            getAllCitys:function(){
                return allcitys;
            },
            getInforData:function(){
                return inforData;
            },
            getCarbrandList:function(){
                return carbrand;
            },
            getCarNums:function(){
                return carnums;
            },
            getCurrentCar:function(){
                return currentcar;
            },
            resetCurrentCar:function(){
                currentcar = {brand:'品牌',bid:'',num:'型号',nid:'',carnumber:1,filepath:'',filename:'上传照片，增加竞价积极性',cropper:{}};
                return currentcar;
            },
            getCurrenttab:function(){
                return currenttab;
            },
            getDray:function(){
                return dray;
            },
            resetInforData:function(){
                citys = [];
                currenttab = {state:false};
                dray = {value:'12',bignum:0,smallnum:0};
                inforData = {
                    type:1,//默认零散数量//2整板
                    startCity:'',
                    endCity:'',
                    startCityId:'',
                    endCityId:'',
                    startTime:dd,
                    endTime:dd,
                    username:'',
                    phone:Number(JSON.parse(localStorage.getItem('user')).phone),
                    carnum:[],
                    draynum:[],
                    draytype:[0,0]

                };
                return inforData;
            }

        }
    })
    .factory('AuthenticationService', function() {//记录登录认证状态
        var auth = {
            isLogged: false
        }
        return auth;
    })
    .factory('MyTransferService', function() {//记录登录认证状态
        var mytransferData = {datas:[]};

        return {
            getMytransferData:function(){
                return mytransferData;
            }
        }
    })
    .factory('TokenInterceptor', function ($q, $window, $location, AuthenticationService) {
        return {
            request: function (config) {
                config.headers = config.headers || {};
                if (localStorage.getItem('token')) {//$window.sessionStorage.token
                    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');//$window.sessionStorage.token;
                }
                return config;
            },

            requestError: function(rejection) {
                return $q.reject(rejection);
            },

            /* Set Authentication.isLogged to true if 200 received */
            response: function (response) {
                if (response != null && response.status == 200 && localStorage.getItem('token') && !AuthenticationService.isLogged) {
                    AuthenticationService.isLogged = true;
                }
                return response || $q.when(response);
            },

            /* Revoke client authentication if 401 is received */
            responseError: function(rejection) {
                if (rejection != null && rejection.status === 401 && (localStorage.getItem('token') || AuthenticationService.isLogged)) {
                    /*delete $window.sessionStorage.token;*/
                    /*localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    AuthenticationService.isLogged = false;*/
                    $location.path("login");
                }

                return $q.reject(rejection);
            }
        };
    })
    .factory('CropperService', function() {//存放蹄片裁剪的参数，记录下来到服务器裁剪
        var cropperdata = [{
            scale1:'',
            scale2:'',
            width:'',
            height:'',
            filename:'',
            filepath:'上传照片，增加竞价积极性'
        }];

        return {
            getCropperdata:function(){
                return cropperdata;
            }
        }
    })
;;/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.centerSrvices', [])
    .factory('CenterService',function($http){
        String.prototype.trim = function(){
            return this.replace(/(^\s*)|(\s*$)/g, "");
        }
        return {
            postFileForm:function(params , scope,callback){
                var xhr = new XMLHttpRequest();
                xhr.open("POST" ,params.url , true);
                xhr.setRequestHeader('Authorization','Bearer ' +  localStorage.getItem('token'))//$window.sessionStorage.token
                xhr.upload.addEventListener("progress", function(evt){
                    if (evt.lengthComputable) {
                        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                        //document.getElementById('toast-err').innerHTML = '已上传 '+percentComplete.toString() + '%';
                        scope.loadingTip = '资料正在上传  '+percentComplete.toString() + '%';
                        scope.$apply();
                    }
                }, false);
                xhr.send(params.data);
                xhr.onload = function(e) {
                    if (this.status == 200) {
                        scope.loadingTip = '资料已经上传，请等待人工审核';
                        scope.$apply();
                        setTimeout(function(){
                            scope.loadingTip = '';
                            scope.$apply();
                        } ,5000)
                        callback(JSON.parse(this.responseText))
                    }
                };
            }
            ,info:{
                id:''
                ,nickname:''
                ,address:''
                ,introduce:''
            },
            getAuthState:function(id){
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/users/getAuthState',
                    data:{
                        id:id,
                        type:1
                    }
                });
            }

        }
    })
    ;;/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.orderServices', [])
    .factory('OrderService',function($http){

        var rows = 10;
/*[{
 startstation:'郑州市 金水区'
 ,endstation:'北京市 涧西区'
 ,starttime:'2015-05-05'
 ,endtime:'2015-06-06'
 ,status:2
 ,price:5000
 ,contact:'李小姐'
 ,phone:'1234567891'
 ,note:'总共运3种型号10辆车'
 }]*/

        var total = [0,0];
        var idx = [0,0];
        var order = [[],[]];
        var page = [1,1];
        var param = [{
            rows:5
            ,page:1
            ,status:2
        }
        ,{
                rows:5
                ,page:1
                ,status:3
            }]
        var service = {
            switch:0
            ,noOrders:[false,false]
            ,busy:false
            ,putOrder:function(data ){
                total[service.switch] = data.total;
                order[service.switch] = data.rows;
            }
            ,appendOrder:function(data ){
                total[service.switch] = data.total;
                order[service.switch] = order[service.switch].concat(data.rows);
            }
            ,status:function(){
                return {
                    total:total[service.switch]
                    ,length:order[service.switch].length
                }
            }
            ,order:function(){
                return order[service.switch];
            }
            ,orders:function(){
                return order;
            }
            ,get: function() {
                var i = idx[service.switch];
                return order[service.switch][i];
            }
            ,set:function(o){
                var i = idx[service.switch];
                var obj = order[service.switch][i];
                obj.user = o.user;
                obj.carrier = o.carrier;
                obj.comment = o.comment;
            }
            ,param:function(){
                return param[service.switch];
            }
            ,setIdx:function(i){
                idx[service.switch] = i;
            }
            ,orderDetail:null
            ,comment:null
        }

        return service;
    })
    .factory('BidService' ,function($http){

    });;/**
 * Created by yunpeng on 2015/4/11.
 */
starterModule.directive('ngCropper',['$http','$compile','$state','CropperService',function($http,$compile,$state,CropperService){//自定义指令
    return{
        restrict: 'A',//
        link:function(scope,element,attrs,controller){
            scope.umsg=false;
            scope.upLoad = function(){
                scope.umsg=true;
                if(!file){
                    document.getElementById('progress').innerHTML = '请选择图片';
                    setTimeout(function(){
                        scope.umsg=false;
                        scope.$apply();
                    },3000);
                    return;
                }
                scope.umsg=true;
                document.getElementById('progress').innerHTML = '图片正在上传...';
                var fd = new FormData();
                fd.append("name", "图片");
                fd.append("files", file);

                //scope.$apply();

                var xhr = new XMLHttpRequest();
                if(scope.urltype=='upheader'){
                    fd.append('scale1',$('#dataX').val());
                    fd.append('scale2',$('#dataY').val());
                    fd.append('width',$('#dataWidth').val());
                    fd.append('height',$('#dataHeight').val());
                    xhr.open("POST" ,"/users/uploadHeaderFiles" , true);
                }else{
                    xhr.open("POST" ,"/uploadFiles" , true);
                }

                xhr.setRequestHeader('Authorization','Bearer ' +  localStorage.getItem('token'))//$window.sessionStorage.token
                //alert(xhr.upload.onprogress)
                xhr.upload.addEventListener("progress", function(evt){
                        //alert(0)
                    if (evt.lengthComputable) {
                        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                        document.getElementById('progress').innerHTML = '正在上传... '+percentComplete.toString() + '%';
                    }


                }, false);
                /*xhr.upload.onprogress = function(evt){
                        alert(0)
                    if (evt.lengthComputable) {
                        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                        document.getElementById('progress').innerHTML = '正在上传... '+percentComplete.toString() + '%';
                    }


                }*/
                xhr.send(fd);
                xhr.onload = function(e) {
                    if (this.status == 200) {
                        //文件上传完成
                        var filename = this.responseText;
                        document.getElementById('progress').innerHTML = '图片已上传完成...'
                            setTimeout(function(){
                            if(scope.urltype=='transfer'){
                                CropperService.getCropperdata()[0] = {
                                    scale1:$('#dataX').val(),
                                    scale2:$('#dataY').val(),
                                    width:$('#dataWidth').val(),
                                    height:$('#dataHeight').val(),
                                    filename:filename,
                                    filepath:filename.substring(0,10)+'.jpg'
                                };
                                $state.go('tab.transferAddCar');
                            }else{
                               var user = JSON.parse(localStorage.getItem('user'));
                                user.headerpath = filename;
                                //alert( user.headerpath);
                                localStorage.setItem('user',JSON.stringify(user));
                                $state.go('tab.center');
                            }
                        },2000);

                    }
                };
            }

            $('.eg-wrapper').css('height',$(window).height()-88+'px');
            var $image = $(".cropper"),
                $dataX = $("#dataX"),
                $dataY = $("#dataY"),
                $dataHeight = $("#dataHeight"),
                $dataWidth = $("#dataWidth"),
                console = window.console || {log:$.noop},
                cropper,
                file;

            $image.cropper({
                aspectRatio: scope.scale1 / scope.scale2,
                // autoCropArea: 1,
                data: {
                    x: 80,
                    y: 60,
                    width: scope.width,
                    height:scope.height
                },
                //preview: ".preview",

                // multiple: true,
                // autoCrop: false,
                // dragCrop: false,
                // dashed: false,
                // modal: false,
                // movable: false,
                // resizable: false,
                // zoomable: false,
                // rotatable: false,
                // checkImageOrigin: false,

                // maxWidth: 480,
                // maxHeight: 270,
                // minWidth: 160,
                // minHeight: 90,

                done: function(data) {
                    /*$dataX.val(data.x);
                     $dataY.val(data.y);
                     $dataHeight.val(data.height);
                     $dataWidth.val(data.width);*/
                    $dataX.val(Math.round(data.x));
                    $dataY.val(Math.round(data.y));
                    $dataHeight.val(Math.round(data.height));
                    $dataWidth.val(Math.round(data.width));
                },

                build: function(e) {
                    console.log(e.type);
                },

                built: function(e) {
                    console.log(e.type);
                },

                dragstart: function(e) {
                    console.log(e.type);
                },

                dragmove: function(e) {
                    console.log(e.type);
                },

                dragend: function(e) {
                    console.log(e.type);
                }
            });

            cropper = $image.data("cropper");

            $image.on({
                "build.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                },
                "built.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                },
                "dragstart.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                },
                "dragmove.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                },
                "dragend.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                }
            });

            $("#reset").click(function() {
                $image.cropper("reset");
            });

            $("#reset2").click(function() {
                $image.cropper("reset", true);
            });

            $("#clear").click(function() {
                $image.cropper("clear");
            });

            $("#destroy").click(function() {
                $image.cropper("destroy");
            });

            $("#enable").click(function() {
                $image.cropper("enable");
            });

            $("#disable").click(function() {
                $image.cropper("disable");
            });

            $("#zoom").click(function() {
                $image.cropper("zoom", $("#zoomWith").val());
            });

            $("#zoomIn").click(function() {
                $image.cropper("zoom", 0.1);
            });

            $("#zoomOut").click(function() {
                $image.cropper("zoom", -0.1);
            });

            $("#rotate").click(function() {
                $image.cropper("rotate", $("#rotateWith").val());
            });

            $("#rotateLeft").click(function() {
                $image.cropper("rotate", -90);
            });

            $("#rotateRight").click(function() {
                $image.cropper("rotate", 90);
            });

            var $inputImage = $("#inputImage");

            if (window.FileReader) {
                $inputImage.change(function() {
                    var fileReader = new FileReader(),
                        files = this.files;
                        //file;

                    if (!files.length) {
                        return;
                    }

                    file = files[0];

                    if (/^image\/\w+$/.test(file.type)) {
                        fileReader.readAsDataURL(file);
                        fileReader.onload = function () {
                            $image.cropper("reset", true).cropper("replace", this.result);
                            $inputImage.val("");
                        };
                    } else {
                        showMessage("Please choose an image file.");
                    }
                });
            } else {
                $inputImage.addClass("hide");
            }

            $("#setAspectRatio").click(function() {
                $image.cropper("setAspectRatio", $("#aspectRatio").val());
            });

            $("#replace").click(function() {
                $image.cropper("replace", $("#replaceWith").val());
            });

            $("#getImageData").click(function() {
                $("#showImageData").val(JSON.stringify($image.cropper("getImageData")));
            });

            $("#setData").click(function() {
                $image.cropper("setData", {
                    x: $dataX.val(),
                    y: $dataY.val(),
                    width: $dataWidth.val(),
                    height: $dataHeight.val()
                });
            });

            $("#getData").click(function() {
                $("#showData").val(JSON.stringify($image.cropper("getData")));
            });

            $("#getData2").click(function() {
                $("#showData").val(JSON.stringify($image.cropper("getData", true)));
            });

            $("#getDataURL").click(function() {
                var dataURL = $image.cropper("getDataURL");

                $("#dataURL").text(dataURL);
                $("#showDataURL").html('<img src="' + dataURL + '">');
            });

            $("#getDataURL2").click(function() {
                var dataURL = $image.cropper("getDataURL", "image/jpeg");

                $("#dataURL").text(dataURL);
                $("#showDataURL").html('<img src="' + dataURL + '">');
            });

            $("#getDataURL3").click(function() {
                var dataURL = $image.cropper("getDataURL", {
                    width: 160,
                    height: 90
                });

                $("#dataURL").text(dataURL);
                $("#showDataURL").html('<img src="' + dataURL + '">');
            });
        }
    }
}]);;/**
 * Created by easezhi on 2015/4/24.
 */

/**
 * jquery实现的网页弹窗，传入需要显示的消息字符串或者dom对象，以及样式
 * @param v
 * @param op
 * @returns {{close: Function, hide: Function, show: Function}}
 */

function toast(v ,op){
    if(!op){
        op = {}
    }
    var sWidth = screen.availWidth;
    var sHeight = screen.availHeight;
    var wWidth = window.innerWidth;
    var wHeight = window.innerHeight;

    var wrapper = $('<div></div>')
    wrapper.css({
        position:'fixed'
        ,'z-index':'5000'
    })

    //预显示内容装入toast，如果消息内容是dom元素，就直接显示
    var conReg = /(^<\w+.*>.*<\x2f\w+>$|^<\w+.*\x2f\s*>$)/;
    if(typeof v == 'string' && !conReg.test(v)){

        var textWrapper = $('<span style="line-height:2.2;padding:0 0.6em;"></span>')
        textWrapper.text(v);
        wrapper.html(textWrapper)
        wrapper.css({
            'background-color':op['bgColor'] || '#ccc'
            ,color:op.color || '#333'
            ,'border-radius':op['radius'] || '5px'
        })
    }
    /*wrapper.html(v)
     wrapper[0].innerHTML = v;*/
    wrapper.append($(v))


    //把预显示内容添加到body元素
    $(document.body).append(wrapper)

    //根据预显示内容的宽高进行定位
    var width = wrapper.width();
    var left = wWidth*0.5 - width*0.5;
    var pos = {left: left+'px'}//默认左偏移
    if(op.left || op.left===0 || op.right || op.right===0){
        pos.left = op.left;
        pos.right = op.right;
    }

    switch (op.pos){
        case 'top':pos.top = op.top || wHeight*0.2+'px';break;
        case 'bottom':pos.bottom = op.bottom || wHeight*0.2+'px';break;
        default :
            var height = wrapper.height();//数字类型的值
            var top = window.innerHeight*0.5 - height*0.6;
            if(top < 70){top = 70}
            if(op.top || op.top===0 || op.bottom || op.bottom===0){
                pos.top = op.top;
                pos.bottom = op.bottom;
            }else{
                pos.top = top+'px';
            }

    }
    wrapper.css(pos)

    //类型是toast，默认自动关闭，timeout 2000毫秒，设timeout为0禁止自动关闭
    var timeout = 0;
    if(!(op.timeout===0)){
        timeout = op.timeout || 2000;
        if(op.type == 'toast' || op.type == undefined ){
            setTimeout(function(){
                t.close();
            },timeout)
        }
    }

    //类型是popup,点击页面其他位置关闭
    var veil = $('<div></div>')//遮幕
    veil.css({
        position:'fixed'
        ,'z-index':4900
        ,width:wWidth
        ,height:sHeight
        ,'background-color':op.veilColor || 'rgba(0,0,0,0)'
        ,top:0
        ,left:0
    })

    if(op.type == 'popup' ){
        $(document.body).append(veil)
        if(!op.disableClose){
            veil.click(function(){
                t.close();
            })
        }
    }

    //类型是弹出窗口，可选右上角的关闭按钮
    if(op.hasCloseBtn==true || op.type=='dialog' && !(op.hasCloseBtn===false)){
        $(document.body).append(veil)
        var btnWrapper = $('<div></div>')
        var btn = $('<div>X</div>')
        btnWrapper.css({
            position:'absolute'
            ,top:'-13px'
            ,right:'-13px'
            ,padding:'3px'
        })
        btn.css({
            width:'20px'
            ,'text-align':'center'
            ,'line-height':'20px'
            ,'border-radius':'50%'
            ,'background-color':op.btnColor || '#999'
            ,color:'#fff'
            ,'font-family': '"微软雅黑",sans-serif'
        })
        wrapper.append(btnWrapper)
        btnWrapper.append(btn)
        btnWrapper.click(function(){
            t.close();
        })

    }

    var t = {
        close:function(){
            if(typeof op.onClose == 'function'){
                var res = op.onClose();
                if(res===false){
                    return;
                }
            }
            wrapper.remove();
            veil.remove()
        }
        ,hide:function(){
            wrapper.hide();
            veil.hide();
        }
        ,show:function(){
            wrapper.show();
            veil.show();
        }
    }
    return t;
}